简体   繁体   English

C#-为什么此循环的第一次迭代比其他循环慢?

[英]C# - Why does the first iteration of this loop run slower than the rest?

I'm doing a bit of benchmarking to test something. 我正在做一些基准测试来测试某些东西。 I've got a large array of 100 million 64 bit ints, I randomly choose 10 million of those and do a few operations. 我有1亿个64位int数组,我随机选择其中的1000万个并执行一些操作。 The indexes are randomly chosen because I'm trying to keep the CPU from caching as much as I can, while still getting an accurate benchmark. 索引是随机选择的,因为我试图在保持准确基准的同时尽量避免CPU缓存。 The first iteration of the loop takes about .3 seconds, with all of the others only taking .2 seconds. 循环的第一次迭代大约需要0.3秒,而所有其他迭代只需要0.2秒。 My only guess is that parts of cone[] are still in cache, but I would think with an array of that size it wouldn't be able to store so much. 我唯一的猜测是锥体[]的部分仍在缓存中,但是我认为如果使用这种大小的数组,将无法存储太多内容。 Any other thoughts? 还有其他想法吗?

Perhaps a JIT issue? 也许是准时制问题?

static void Main(string[] args)
    {

        Int64[] cone = new Int64[100000001];

        for (int m = 0; m < 20; ++m)
        {
            int[] num2 = new int[10000001];
            Random rand = new Random();

            for (int i = 0; i < 10000000; ++i)
            {
                num2[i] = rand.Next(100000000);
            }

            DateTime start = DateTime.Now;

            for (int i = 0; i < 10000000; ++i)
            {
                cone[num2[i]] = i;
                if (cone[i] > 0) ++cone[i];

            }

            DateTime finish = DateTime.Now;
            TimeSpan elapsed = finish - start;

            Console.WriteLine("Took: {0}", elapsed);
            Thread.Sleep(100);
        }
        Console.ReadLine();
    }

May be the code is Jitted the first time you hit the loop. 可能是您第一次碰到循环时代码被激怒了。 The compile time is what's making it slow? 编译时间是什么使它变慢? I ran a C++ version of your code and it seems to have about the same latency for every iteration. 我运行了C ++版本的代码,每次迭代的延迟似乎都相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM