I have short code that performs different operations and I want to measure the time that takes to perform each. I read here about Stopwatch class, and wanted to optimize my time measurements. my functions calls 5 other functions and I want to measure each without declaring :
stopwatch sw1 = new stopwatch();
stopwatch sw2 = new stopwatch();
etc..
my function looks like that:
public bool func()
{
....
func1()
func2()
....
....
func5()
}
is there any way to measure the time using one stopwatch instance?
thanks!!
Use delegates to pass a method as a parameter to a function.
Here I used Action Delegates as the methods specified does not return a value.
You can modify it accordingly if your method has a return type or parameter by using a Function delegate
static void Main(string[] args)
{
Console.WriteLine("Method 1 Time Elapsed (ms): {0}", TimeMethod(Method1));
Console.WriteLine("Method 2 Time Elapsed (ms): {0}", TimeMethod(Method2));
}
static long TimeMethod(Action methodToTime)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
methodToTime();
stopwatch.Stop();
return stopwatch.ElapsedMilliseconds;
}
static void Method1()
{
for (int i = 0; i < 100000; i++)
{
for (int j = 0; j < 1000; j++)
{
}
}
}
static void Method2()
{
for (int i = 0; i < 5000; i++)
{
}
}
}
By using this you could pass any method you want.
Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With