C# - 为什么此循环的第一次迭代比其余循环运行得慢?

发布于 2024-11-06 21:35:02 字数 1025 浏览 4 评论 0原文

我正在做一些基准测试来测试一些东西。我有一个包含 1 亿个 64 位整数的大数组,我随机选择其中的 1000 万个并进行一些操作。索引是随机选择的,因为我试图尽可能阻止 CPU 进行缓存,同时仍然获得准确的基准测试。循环的第一次迭代大约需要 0.3 秒,所有其他迭代只需要 0.2 秒。我唯一的猜测是,cone[] 的部分内容仍在缓存中,但我认为对于该大小的数组,它无法存储这么多。还有其他想法吗?

也许是 JIT 问题?

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();
    }

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. 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. The first iteration of the loop takes about .3 seconds, with all of the others only taking .2 seconds. 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();
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉世弥音 2024-11-13 21:35:02

可能是代码在您第一次进入循环时被即时编译。编译时间是什么让它变慢的?我运行了你的代码的 C++ 版本,它似乎每次迭代都有大约相同的延迟。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文