Prevent context-switching in timed section of code (or measure then subtract time not actually spent in thread)

你。 提交于 2019-12-03 14:22:22

You can't do that. Otherwise it would be very easy for any application to get complete control over the CPU timeslices assigned to it.

You can, however, give your process a high priority to reduce the probability of a context-switch.


Here is another thought:
Assuming that you don't measure the execution time of a regular expression just once but multiple times, you should not see the average execution time as an absolute value but as a relative value compared to the average execution times of other regular expressions.
With this thinking you can compare the average execution times of different regular expressions without knowing the times lost to context switches. The time lost to context switches would be about the same in every average, assuming the environment is relatively stable with regards to CPU utilization.

I don't think you can do that.

A "best effort", for me, would be to put your method in a separate thread, and use

Thread.CurrentThread.Priority = ThreadPriority.Highest; 

to avoid as much as possible context switching.

If I may ask, why do you need such a precise measurement, and why can't you extract the function, and benchmark it in its own program if that's the point ?

Edit : Depending on the use case it may be useful to use

Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2); // Or whatever core you want to stick to

to avoid switch between cores.

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