cost
cost

Reputation: 4480

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

Upvotes: 2

Views: 635

Answers (1)

Aater Suleman
Aater Suleman

Reputation: 2328

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.

Upvotes: 5

Related Questions