Why is await async so slow?

前端 未结 4 1061
粉色の甜心
粉色の甜心 2020-12-14 18:27

I finally got VS2012 and got a simple demo up and working to check out the potential performance boost of async and await, but to my dismay it is slower! Its possible I\'m d

4条回答
  •  生来不讨喜
    2020-12-14 19:14

    Your benchmark has a couple of flaws:

    • You are timing the first run which includes initialization time (loading class Task, JIT-compilation etc.)
    • You are using DateTime.Now, which is too inaccurate for timings in the millisecond range. You'll need to use StopWatch

    With these two issues fixed; I get the following benchmark results:

    Regular Sum:  499946 in 00:00:00.0047378
    Async Sum:    499946 in 00:00:00.0016994
    Threaded Sum: 499946 in 00:00:00.0026898
    

    Async now comes out as the fastest solution, taking less than 2ms.

    This is the next problem: timing something as fast as 2ms is extremely unreliable; your thread can get paused for longer than that if some other process is using the CPU in the background. You should average the results over several thousands of benchmark runs.

    Also, what's going on with your number of core detection? My quad-core is using a chunk size of 333334 which allows only 3 threads to run.

提交回复
热议问题