问题描述
我有一个多线程应用程序,在代码的某些部分中,我使用Stopwatch
来衡量操作时间:
I have a multi-threaded application, and in a certain section of code I use a Stopwatch
to measure the time of an operation:
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 if the program switches control to another thread somewhere else while the stopwatch is started, then the timed duration will be wrong. The other thread could have done any amount of work before the context switches back to this section.
请注意,我并不是在询问锁定,因为它们都是局部变量,所以没有必要.我只希望定时部分可以连续执行.
Note that I am not asking about locking, these are all local variables so there is no need for that. I just want the timed section to execute continuously.
edit:另一种解决方案可能是减去上下文切换时间,以获得在定时部分中完成工作所需的实际时间.不知道那是不可能的.
edit: another solution could be to subtract the context-switched time to get the actual time done doing work in the timed section. Don't know if that's possible.
推荐答案
您不能这样做.否则,任何应用程序都将很容易获得对分配给它的CPU时间片的完全控制.
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.
这是另一种想法:
假设您不只是一次而是多次测量一个正则表达式的执行时间,那么与其他正则表达式的平均执行时间相比,您不应将平均执行时间视为一个绝对值,而是一个相对值. >通过这种想法,您可以比较不同正则表达式的平均执行时间,而无需了解上下文切换所浪费的时间.假设环境在CPU利用率方面相对稳定,那么上下文切换所损失的时间在每个平均值上大约是相同的.
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.
这篇关于防止在代码的定时部分中进行上下文切换(或进行度量,然后减去线程中未实际花费的时间)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!