Repository navigation
Description
I've used trio in some projects lately, and also recently added it to dnspython. As part of some random performance testing, I compared "minimal DNS server" performance between ordinary python sockets, curio, and trio. I'll attach the trio program to the bottom of this report. Trio performed significantly worse. E.g. on a particular linux VM:
Regular python I/O: 9498 QPS
Curio: 8979 QPS
Trio: 5007 QPS
I've seem similar behavior on a Mac:
Regular python I/O: 8359 QPS
Curio: 8061 QPS
Trio: 3425 QPS
I'm using dnsperf to generate load, and it does a good job of keeping UDP input queues full, so the ideal expected behavior if you strace the program is to see a ton of recvfrom() and sendto() system calls, and nothing else. In particular, you don't expect to see any epoll_wait(). Ordinary python I/O and curio behave as expected, but going through the loop in trio looks like:
recvfrom()
clock_gettime()
epoll_wait() (not waiting on any fds if I'm reading strace output correctly)
clock_gettime()
clock_gettime()
epoll_wait()
clock_gettime()
sendto()
clock_gettime()
epoll_wait()
clock_gettime()
I don't understand trio's internals enough to debug this further at the moment, but I thought I would make a report, as this seems like excessive epolling.
I haven't dtrussed on the mac, but python tracing indicated a lot of time related to kqueue.
This was with trio 0.15.1, and Cpython 3.8.3 and 3.7.7.
import socket
import trio
import trio.socket
import dns.message
import dns.rcode
async def serve():
with trio.socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
await s.bind(('127.0.0.1', 5354))
while True:
(wire, where) = await s.recvfrom(65535)
q = dns.message.from_wire(wire)
r = dns.message.make_response(q)
r.set_rcode(dns.rcode.REFUSED)
await s.sendto(r.to_wire(), where)
def main():
trio.run(serve)
if __name__ == '__main__':
main()
Activity
rthalley commentedon Jun 9, 2020
P.S. I enjoy trio, keep up the good work!
rthalley commentedon Jun 9, 2020
Also, if you want to generate the load, create a file called input with one line
www.example A
and then run
dnsperf -d input -p 5354 -l 10
rthalley commentedon Jun 10, 2020
Note I wasn't reading the strace output correctly about whether epoll matched any fds or not; I just don't know. If there's anything you want me to test let me know :)
rthalley commentedon Jun 10, 2020
One last comment today :)
So, I read some trio code, and while I don't fully understand the details, it seems to me that the difference between curio and trio here is that curio only schedules if the system call would block, whereas trio introduces a schedule point after every I/O call. The curio way can starve other tasks as a sufficiently busy task might never block, whereas the trio way can result in excessive scheduling resulting in significantly lower throughput. This is a tough thing, and hard for a library to decide what's best. In the curio style world, the application can count how many loops it has done and sleep(0) every (say) 100 calls and avoid a lot of not helpful scheduler overhead while still not starving other tasks, but if you forget it can be bad.
I wonder if there could be a scoped I/O mode in trio where within the scope you would schedule if you had to (i.e. the system call would block), but if you didn't have to it would NOT schedule until you'd hit some specified count of schedule points.
e.g.
async with trio.defer_schedule_limit(100):
await io()
This would allow applications that want to be more aggressive with I/O do so, while still letting the default behavior be safe.
m-u-xyz commentedon Jun 10, 2020
That'd be useful. Alternately we could use a time limit (or the perf counter) which would be more deterministic for the rest of the code.
Add a fast path for the simplest cases of socket address resolution
Add a fast path for the simplest cases of socket address resolution
njsmith commentedon Jun 15, 2020
👋 Hello!
Trio is definitely not yet as fast as it could be, or as we want it to be. Partly this is following the old rule "first make it right, then make it fast", and partly it's because it's hard to optimize things well without good benchmarks to profile. So this benchmark is super helpful :-)
Trio does do more schedules and IO polls than curio, but I'm not sure how much that actually contributes to what you're seeing. Running your benchmark through py-spy, the first thing that jumped out at me is that we were spending a tremendous amount of time in
getaddrinfo, which doesn't make any sense, since your program doesn't use any hostnames...It turns out that the issue was that when you call
trio_socket.sendto(..., address), then Trio picks apartaddressand resolves any hostnames it finds before it calls the underlying Pythonsocket.sendto. If it didn't do that, and just passed the address through directly, thensocket.sendtowould implicitly do a blocking DNS lookup for any hostnames, and block the whole program. So the basic idea is good... but we were assuming that callinggetaddrinfoon an already-resolved literal IP address was basically free, and it turns out that that's false (at least on Linux). So that's fixed in #1617 by adding a fast-path to skip callinggetaddrinfoentirely whenever we can.(Asyncio has a similar optimization already. Curio doesn't try to resolve hostnames in addresses at all; it just passes through whatever address you use directly to the stdlib
socketmodule. Which of course is the fastest thing, but it means that users just have to know to manually resolve their hostnames before calling into curio socket methods, and if you forget it will seem to work but you'll get random stalls.)I don't know how much of the gap between curio/sync python that fixes, but it might be interesting to re-run your benchmarks on the latest Trio checkout and see :-).
After fixing that, the next big thing that shows up in the profile for me is the complex metaprogramming stuff we use in
trio.socketto try to reduce boilerplate (if you're curious, check out_try_sync,_nonblocking_helper,_make_simple_sock_method_wrapper). It does reduce boilerplate, but it adds a bunch of runtime overhead, so we've been planning for a while to switch to using code-generation to write out all the boilerplate directly. That's a somewhat bigger job though, so it will wait until someone gets around to it. (Volunteers welcome :-).)Once we've fixed that, we'll have a better sense of how much overhead those extra schedules are adding... in my profile it looks like it's only ~5% of the CPU time currently, but it's kind of hard to estimate, b/c schedule points have a diffuse cost. But we certainly could explore options like "skip bare checkpoints if we've already done one within the last 0.5 ms" or so. We just need some good data to compare the different options.
rthalley commentedon Jun 15, 2020
I checked out master branch from github this morning and installed it on the same system I used for testing before. There was some improvement, from the 5007 QPS with 0.14 to 5750 QPS.
I wonder if py-spy was missing something (e.g. C calls) because I used python's cProfile module and what I see from the dnsperf load is epoll is the biggest cost. I tend to believe that epoll() is the actual issue because of how frequently it is called, and because of prior experience with cooperative multitasking in C. I had the load running before I started the python server, and I had the server bail out while the load was still running, so the times sampled in epoll should reflect actual costs.
rthalley commentedon Jun 15, 2020
Also I note that number 2 on the list was _nonblocking_helper(). Given we're not taking any of the BlockingIOError paths, I'm guessing the cost here is related to the invocation of the scheduler after every I/O in the aexit of _try_sync. (This is consistent with the gettimeofday() and epoll_wait() system calls I see between recvfrom() and then sendto().)
njsmith commentedon Jun 16, 2020
In my experience, trying to use intuition to speed things up will often send you off down blind alleys... it's important to focus on data :-).
Also I generally avoid cProfile, because (a) it's not very accurate (it adds a lot of per-function overhead, so it tends to tell you to replace all your small functions with big functions, regardless of whether that will actually speed up your program or not), (b) it's not very useful (to get a clear picture of what's going on you really need your profiler to show call stacks, not just individual functions). I like sampling call-stack profilers like py-spy or pyinstrument. (And FWIW py-spy at least captures C call stacks as well, though it's not super relevant here b/c we don't use many extension modules.)
That said: your cProfile data is claiming that
epoll.pollis responsible for 2.4% of the total runtime. So those epoll calls are a factor, but they don't explain why trio is 2x slower than curio/sync code :-). We have to keep digging.The extra schedules are a part of that: the cost of those includes the epoll calls, but also other administrivia like checking for timeouts, pausing/resuming tasks, etc. Exactly how much I'm not certain.
rthalley commentedon Jun 16, 2020