不一致的CPU性能的简单的2行程序。 C#.NET 4.0行程、性能、简单、CPU

2023-09-04 02:32:49 作者:|▌春风中飘过多少往事

这里有一个问题,我有。我有一台服务器和一台笔记本电脑。所有的电脑都在其上运行什么。

Here's a problem I'm having. I've a server and a laptop. Both computers have nothing running on them.

下面的程序:

    static void Main( string[] args )
    {
        Stopwatch w = new Stopwatch();
        while( true )
        {
            w.Restart();
            for( int i = 0; i < int.MaxValue; i++ )
                ;

            w.Stop();

            System.Console.WriteLine( w.ElapsedMilliseconds );
        }
    }

在我的笔记本电脑,我得到大约650毫秒一致的性能。在服务器上,我得到疯狂的波动。任何东西,从595到1500毫秒。同样的电脑都没有在其上运行。该计划是如此简单,它甚至不使用RAM。只需注册可能。

On my laptop I get consistent performance around 650 miliseconds. On the server I get crazy swings. Anything from 595 to 1500 miliseconds. Again both computers have nothing running on them. The program is so simple it doesn't even use RAM. Just registers probably.

这是什么原因?我测试服务器,并使用passmark.com基准笔记本电脑,一切看起来正常。

What can cause this? I tested the server and the laptop with passmark.com benchmark and everything looks normal.

下面是规格为服务器: 视窗2012 64 CPU:至强e5-1620 @ 3.6

Here are the specs for the server: windows 2012 x64 cpu: xeon e5-1620 @ 3.6

下面是规格为笔记本: Windows 7的64位 CPU:睿i7-2620M @ 2.7

Here are the specs for the laptop: windows 7 x64 cpu: i7-2620M @ 2.7

Windows 7的睿i7-2620M截图

视窗2012至强e5-1260截图

推荐答案

秒表测量性能不是太precise,特别是在更先进的系统,因为先进的硬件时机取决于很多事情,通常不直接控制下的程序,比如内核之间的迁移,您的进程和线程,缓存亲和力,各种CPU的流水线的状态,等优先。

Measuring performance with Stopwatch is not too precise, especially on more advanced systems, because on advanced hardware the timing depends a lot on things that are not usually under direct control of your program, such as migrations between cores, priority of your processes and threads, cache affinity, state of various CPU pipelines, and so on.

尝试添加这些指令(的从这里)启动秒表前:

Try adding these instructions (from here) before starting the stopwatch:

Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
Thread.CurrentThread.Priority = ThreadPriority.Highest;

这应该使测量更加一致,特别是在多核心,多CPU盒。

This should make the measurements more consistent, especially on multi-core, multi-cpu boxes.