Why measuring the execution time of a loop gives different results execution after execution? [duplicate]

橙三吉。 提交于 2020-07-10 09:37:12

问题


I know it's stupid, but I still have to ask this question because it's been bothering me for days.

I use a variety of methods to test, but the results vary widely.

The execution time of a million double-int conversions is the same as empty loop


回答1:


Good and smart question.

The Elapsed result of a StopWatch varies because modern computers and modern Operating Systems, even on smartphones now, unlike old Dos, are multitask.

So while you do your loop and measure it, some other software processes having software threads run at the same time, as well as the OS kernel itself.

Modern CPU are able to execute several instructions at same time: one per real core. False cores or hardware threads use a context saving system named Hyper-Threading for Intel's CPU. For example Intel sells a Core i7-4770 having 4 cores and 8 threads, two per core.

Multithreading is inside a processes. Multiprocessing is for processes. They are both multitasking. A process is the application launched and it can have some threads. Multitasking is the capacity of the CPU to execute several instructions at the same time. For example Windows 10 on modern Intels supports both multiprocessing and multithreading.

Computer multitasking

True multitasking

CPU multitasking

If you measure a loop in Dos mono-task, you'll get the same result run after run.

But in multitask OS, you should do some runs, say a dozen or a half, and take the avarage.

Hence while you measure a loop, all running processes having registered to system events receive notifications, the kernel do something, the windows explorer too, and all others running apps too... as the task manager and the CPU manage all these running processes as well as I/O interrupts like keyboard and mouse events and drive operations, and drivers like graphic outpout.


You can also read these answers which explain most of the ramp-up where early iterations are slow.

  • Why does this delay-loop start to run faster after several iterations with no sleep
  • Why can't my CPU maintain peak performance in HPC

Running a loop in full speed does produce various results too, and that can come from an interrupt handler happening to run or not, if you're measuring over very short intervals instead of averaging over a long run time.



来源:https://stackoverflow.com/questions/58678348/why-measuring-the-execution-time-of-a-loop-gives-different-results-execution-aft

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!