Sheer
Sheer

Reputation: 23

For loop randomly takes more ticks?

I was testing my code to see the performance difference between a for and a foreach loop (wanted to see how it impacted my program out of curiosity) and, while measuring the ticks, I noticed that there would be a sporadic jump in the time it took when the list was empty in a for loop.

For example, some of the output in the console window reads [...], 2, 4, 4, 2, 5, 4, 2, 26, 3, 1, 27, 2, 2, 1, 3, 2, 2, [...].

While I realize that these ticks for such a small time interval measurement are negligent on the final performance of my application, I'm curious as to why there's such a jump. Again, these numbers were taken while I knew the list was empty, so there was nothing to actually iterate over.

The objects in the loop are dictionaries; specifically, they have ints for keys and custom classes for their values.

Stopwatch.Frequency gives me 2533211 (I have not had to restart my system since I took the previous measurements).

Code -

    public void Update(int gameTime)
    {
        watch.Restart();
        for (int i = 0; i < _movementComponents.Count; ++i)
        {
            _positionComponents[i].Position += _movementComponents[i].Velocity * gameTime;
            _movementComponents[i].Velocity = Vector2.Zero;
        }
        watch.Stop();
        Console.WriteLine("Loop took " + watch.ElapsedTicks + " ticks");
    }

Upvotes: 1

Views: 189

Answers (1)

usr
usr

Reputation: 171178

I did such an experiment with an empty loop. The same random delays are found there as well. Here are a few reasons for them that I can think of:

  • Interrupts (network, mouse, timer ticks, IO completions caused by other processes, music player, USB device isochronous transfers, ...)
  • High priority threads doing tiny amounts of work before going to sleep. I can't think of any concrete such thread but I know this is a reason. When you set your own thread and process to realtime the latency profile is significantly compressed.
  • Maybe you're touching memory pages that are on the standby list. This means that a soft page fault occurs on access.
  • The Garbage Collector might be triggered my something other than this loop.

Upvotes: 1

Related Questions