Question

When I make an array containing methods, stopwatch.elapsedMilliseconds always returns 0.

Example:

int[] methods = {method1(), method2()};

Stopwatch sw = new Stopwatch();

sw.Start();
int val = methods[1];
sw.Stop();

Console.WriteLine("It took {0} ms", sw.ElapsedMilliseconds);
// Output: "It took 0 ms"

When i just call the method directly, then the stopwatch works properly:

Stopwatch sw = new Stopwatch();

sw.Start();
method1();
sw.Stop();

Console.WriteLine("It took {0} ms", sw.ElapsedMilliseconds);
// Output: "It took x ms"

What am I doing wrong?

Edit: Actual main code:

 static void Main(string[] args)
        {
            Stopwatch t = new Stopwatch();
            Func<int>[] problems = new Func<int>[] { problem5, problem6 };


            for (int i = 0; i < problems.Length; i++)
            {
                t.Restart();
                Console.WriteLine("Solution to {0} is: {1}", problems[i].Method.Name , problems[i]());
                t.Stop();
                Console.WriteLine("It took {0} ms ", t.ElapsedMilliseconds);


            }

            Console.ReadKey();


        }

Output: http://puu.sh/3Znwd.png

Was it helpful?

Solution

int[] methods = new[] { method1(), method2() };

This one calls directly method1() and method2() BEFORE your Stopwatch!

Try

Func<int>[] methods = new Func<int>[] { method1, method2 };

t.start();
methods[1]();

Example

Func<int>[] methods = new Func<int>[] { method1, method2 };

Stopwatch sw = new Stopwatch();

for(int i = 0; i < methods.Length; i++)
{
    sw.Restart(); // or sw.Reset(); sw.Start();
    methods[i]();
    sw.Stop();

    Console.WriteLine("{0} took {1} ms", allMethods[i].Method.Name, sw.ElapsedMilliseconds);      
}

OTHER TIPS

I assume you're trying to benchmark a group of methods that return ints. You can do something like this

Func<int>[] allMethods = new Func<int>[] { method1, method2 };

Stopwatch sw = new Stopwatch();
for(int i =0; i < allMethods.Length; i++)
{
    sw.Restart(); 
    allMethods[i]();
    sw.Stop();

    Console.WriteLine("{0} took {1} ms", allMethods[i].Method.Name, sw.ElapsedMilliseconds);      
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top