Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use StopWatch multiple times in C#?

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!!

like image 803
user1386966 Avatar asked Aug 08 '13 06:08

user1386966


1 Answers

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!

like image 66
Andrei dela Cruz Avatar answered Sep 17 '22 17:09

Andrei dela Cruz