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

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


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.