Prevent context switching in the time section of the code (or measure and then subtract the time that was not actually spent in the stream)

I have a multi-threaded application, and in a specific section of the code I use Stopwatch to measure the operation time:

 MatchCollection matches = regex.Matches(text); //lazy evaluation Int32 matchCount; //inside this bracket program should not context switch { //start timer MyStopwatch matchDuration = MyStopwatch.StartNew(); //actually evaluate regex matchCount = matches.Count; //adds the time regex took to a list durations.AddDuration(matchDuration.Stop()); } 

Now the problem is that the program switches to another thread somewhere else when the stopwatch starts, then the wait time will be incorrect. Another thread could do any work before the context switches to this section.

Please note that I am not asking about locking, these are all local variables, so there is no need for this. I just want the temporary section to run continuously.

edit: another solution could be to subtract time with context switching to get the actual execution time in the time section. I don’t know if this is possible.

+4
source share
2 answers

You cannot do this. Otherwise, for any application, it would be very easy to get full control over the CPU time series assigned to it.

However, you can give your process a high priority to reduce the chance of context switching.


Here is another thought:
Assuming that you do not measure the runtime of a regular expression only once, but several times, you should not see the average runtime as an absolute value, but as a relative value compared to the average runtime of other regular expressions.
With this thinking, you can compare the average runtime of various regular expressions without knowing the time lost for context switches. The time lost for context switches will be approximately the same in each average, assuming that the environment is relatively stable with respect to CPU usage.

+3
source

I do not think you can do this.

The 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 context switching as possible.

If I may ask, why do you need such an accurate measurement, and why you cannot extract this function and not compare it in your own program, if that is 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 switching between cores.

+2
source

Source: https://habr.com/ru/post/1484391/


All Articles