Reputation: 2831
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:
Upvotes: 0
Views: 1434
Reputation: 111940
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);
}
Upvotes: 6
Reputation: 69372
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);
}
Upvotes: 4