-1

That is my first attempt to use StopWatch to meassure code performance and I don't know what is wrong. I want to check if there is difference when casting to double to calculate average with integers.

    public static double Avarage(int a, int b)
    {
        return (a + b + 0.0) / 2;
    }

    public static double AvarageDouble(int s, int d)
    {
        return (double)(s + d) / 2;
    }

    public static double AvarageDouble2(int x, int v)
    {
        return ((double)x + v) / 2;
    }

Code to test these 3 methods, using StopWatch:

        Stopwatch sw = new Stopwatch();

        sw.Start();
        for (int i = 0; i < 1000000; i++)
        {
            var ret = Avarage(2, 3);
        }
        sw.Stop();

        Console.Write("Using 0.0: " + sw.ElapsedTicks + "\n");
        sw.Reset();
        sw.Start();
        for (int i = 0; i < 1000000; i++)
        {
            var ret2 = AvarageDouble(2, 3);
        }
        sw.Stop();
        Console.Write("Using Double(s+d): " + sw.ElapsedTicks + "\n");
        sw.Reset();
        sw.Start();
        for (int i = 0; i < 1000000; i++)
        {
            var ret3 = AvarageDouble2(2, 3);
        }
        sw.Stop();
        Console.Write("Using double (x): " + sw.ElapsedTicks + "\n");

It shows random result, once Average is the fastets, other time AverageDouble or AverageDouble2. I use diff variable names, but looks like it does not matter.

What am I missing?

PS. What is the best method to calculate average with two ints as inputs?

Leszek P
  • 1,807
  • 17
  • 24
  • What do you mean by *random* results? This is working as expected for me – Matias Cicero Nov 15 '15 at 22:44
  • There is no difference, all three versions ask the processor to execute the exact same machine code instructions. What you see is that the processor does not execute code deterministically. Running it on a multi-tasking operating system is a very big part of that, your program is not the only code that runs.. But it goes down as low as the processor itself, it is for example affected by the exact location of the code in memory and the state of the caches. – Hans Passant Nov 15 '15 at 23:01

1 Answers1

2

Tested your code, yes the results was very random at times. Remember Stopwatch is only the time elapsed from sw.start() to sw.stop(). It does not take into consideration .Net's Just In Time compilation, operating system process scheduling, cpu load etc.

This will be more noteworthy in methods with such small runtimes. Where these noises, can more then double the runtime.

An elaborate and better explanation is written in the following SO question.

mrhn
  • 17,961
  • 4
  • 27
  • 46