多处理器机器中秒表的最佳实践? [英] Best Practice for Stopwatch in multi processors machine?

查看:57
本文介绍了多处理器机器中秒表的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个很好的问题 用于测量功能性能,答案建议使用秒表,如下所示

I found a good question for measuring function performance, and the answers recommend to use Stopwatch as follows

Stopwatch sw = new Stopwatch();
sw.Start();
//DoWork
sw.Stop();
//take sw.Elapsed

但是如果您在多处理器机器下运行,这是否有效?线程可以切换到另一个处理器,可以吗?同样的事情也应该在 Enviroment.TickCount 中.如果答案是肯定的,我应该将我的代码包装在 BeginThreadAffinity 中,如下所示

But is this valid if you are running under multi processors machine? the thread can be switched to another processor, can it? Also the same thing should be in Enviroment.TickCount. If the answer is yes should I wrap my code inside BeginThreadAffinity as follows

Thread.BeginThreadAffinity();
Stopwatch sw = new Stopwatch();
sw.Start();
//DoWork
sw.Stop();
//take sw.Elapsed
Thread.EndThreadAffinity();

附言

切换不仅可以在处理器级别发生在线程级别,例如如果函数在另一个线程中运行,系统可以将其切换到另一个处理器,如果发生这种情况,秒表在此切换后是否有效?

The switching can occur over the thread level not only the processor level, for example if the function is running in another thread so the system can switch it to another processor, if that happens, will the Stopwatch be valid after this switching?

我不仅使用秒表进行性能测量,而且还使用 Thread.Sleep 模拟计时器功能(以防止调用重叠)

I am not using Stopwatch for perfromance measurement only but also to simulate timer function using Thread.Sleep (to prevent call overlapping)

推荐答案

如果函数本身不是多线程的(例如,它不会产生其他线程/进程并等待它们完成),那么唯一的问题就是你的机器.

If the function itself isn't multithreaded (eg it doesn't spawn other threads/processes and wait for them to complete) then the only issue is your machine.

如果您的机器忙于做其他事情,它可能会使您的测试无效(例如,在进行 CPU 密集型测试时对 H.264 视频进行编码).同样,如果您使用所有物理内存来测试受内存限制的内容,那么它可能会使您的结果无效.

If your machine is busy doing other things it could invalidate your test (eg encoding a H.264 video while doing a CPU-bound test). Likewise if you use all the physical memory on testing something that is memory-bound then it could invalidate your results.

所以一般原则是,在进行此类测试时,机器应处于最低到正常的负载下.除此之外,没有多处理问题.是的,程序可以在运行时交换内核,但这样做的开销要么是测量时间的一小部分,要么测量时间太小以至于系统时间测量的粒度是一个问题.

So the general principle is that the machine should be under a minimal-to-normal load when conducting such tests. Other than that there isn't a multiprocessing issue. Yes, the program could swap cores while running but the overhead of doing that is either a tiny percentage of your measured time or the measured time is so small that the granularity of the system's time measurement is an issue.

这篇关于多处理器机器中秒表的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆