8

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: 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.

4

2 回答 2

5

你不能那样做。否则,任何应用程序都非常容易完全控制分配给它的 CPU 时间片。

但是,您可以为您的进程提供高优先级以降低上下文切换的可能性。


这是另一个想法:
假设您不只测量一次正则表达式的执行时间,而是多次测量,您不应该将平均执行时间视为绝对值,而是将其视为与其他平均执行时间相比的相对值常用表达。
有了这种想法,您可以比较不同正则表达式的平均执行时间,而无需知道上下文切换所损失的时间。假设环境在 CPU 利用率方面相对稳定,那么在每个平均值中,上下文切换所损失的时间大致相同。

于 2013-06-04T11:58:44.473 回答
2

我不认为你能做到这一点。

对我来说,“尽力而为”是将您的方法放在一个单独的线程中,并使用

Thread.CurrentThread.Priority = ThreadPriority.Highest; 

尽可能避免上下文切换。

如果我可能会问,为什么你需要如此精确的测量,为什么你不能提取函数,并在它自己的程序中对其进行基准测试,如果那是重点的话?

编辑:根据用例,使用它可能很有用

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

以避免内核之间的切换。

于 2013-06-04T12:01:11.397 回答