How do I measure how long a function is running?

C#.NetPerformanceTimerStopwatch

C# Problem Overview


I want to see how long a function is running. So I added a timer object on my form, and I came out with this code:

private int counter = 0;

// Inside button click I have:
timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);
timer.Stop();

And:

private void timer_Tick(object sender, EventArgs e)
{
    counter++;
    btnTabuSearch.Text = counter.ToString();
}

But this is not counting anything. Why?

C# Solutions


Solution 1 - C#

To avoid future problems with a timer, here is the right code:

timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = 1; //set interval on 1 milliseconds
timer.Enabled = true; //start the timer
Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);
timer.Enabled = false; //stop the timer

private void timer_Tick(object sender, EventArgs e)
{
   counter++;
   btnTabuSearch.Text = counter.ToString();
}

But it's the wrong aproach. You must use the Stopwatch (System.Diagnostic) class because it's a High resolution timer and the word Diagnostic says everything.

So try this:

Stopwatch timer = Stopwatch.StartNew();

Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);

timer.Stop();  
TimeSpan timespan = timer.Elapsed;

btnTabuSearch.Text = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10);

Solution 2 - C#

Don't use a timer - use the Stopwatch class.

var sw = new Stopwatch();
Result result = new Result();

sw.Start();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);

sw.Stop();

// sw.Elapsed tells you how much time passed

Solution 3 - C#

The best way to see how long a bit of code takes to run is to use System.Diagnostics.Stopwatch.

Here's an example:

using System.Diagnostics;

#if DEBUG
     Stopwatch timer = new Stopwatch();
     timer.Start();
#endif

     //Long running code

#if DEBUG
     timer.Stop();
     Debug.WriteLine("Time Taken: " + timer.Elapsed.TotalMilliseconds.ToString("#,##0.00 'milliseconds'"));
#endif

I use the #if DEBUG to ensure the stopwatch code doesn't get into the production release, but you could do without it.

Solution 4 - C#

Visual Studio 2015, 2017 Professional and Enterprise has diagnostic tool. If you have a breakpoint at the end of your function, it will display the time and duration under the Events tab as shown in the image:

Enter image description here

You can see the article Diagnostic Tools debugger window in Visual Studio 2015 for more details.

PS; So far only Xamarin forms, cross platform project doesnt support this feature. I wish that Microsoft brings this great feature for xamarin forms projects as well.

Solution 5 - C#

You should use the stopwatch class for timing functions.

Try the following:

private int counter = 0;

// setup stopwatch and begin timing
var timer = System.Diagnostics.Stopwatch.StartNew();

Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);

// stop timer and get elapsed time
timer.Stop();
var elapsed = timer.Elapsed;

// display result time
MessageBox.Show(elapsed.ToString("mm':'ss':'fff"));

Solution 6 - C#

Use Stopwatch of System.Diagnostics:

static void Main(string[] args)
{
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    Thread.Sleep(10000);
    stopWatch.Stop();

    // Get the elapsed time as a TimeSpan value.
    TimeSpan ts = stopWatch.Elapsed;
    
    // Format and display the TimeSpan value.
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
    Console.WriteLine("RunTime " + elapsedTime);
}

Solution 7 - C#

For timing a function, you should use the Stopwatch Class

Also, the reason your timer isn't counting is because you didn't set an interval for it.

Solution 8 - C#

Perhaps, you could write a method like that:

public static void Time(Action action)
{
	Stopwatch st = new Stopwatch();
	st.Start();
	action();
	st.Stop();
	Trace.WriteLine("Duration:" + st.Elapsed.ToString("mm\\:ss\\.ff"));
}

And use it like that:

Time(()=>
{
 CallOfTheMethodIWantToMeasure();
});

Solution 9 - C#

I reviewed and agreed with all suggestions. But wanted to share one generic implementation for execution time logger where we do not want to implement Stopwatch logic multiple times but still wants to measure execution time for multiple methods.

The main reason for not to implement logger in generic way is - method execution is in between stopwatch.Start() and stopwatch.Stop() also we may require method result after the execution for further processing.

So to tackle this issue I created following sample implementation where Execution time is logged separately without mixing it with actual method flow.

public static class Helper
{
    public static T Time<T>(Func<T> method, ILogger log)
    {
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        var result = method();
        stopwatch.Stop();
        log.Info(string.Format("Time Taken For Execution is:{0}", stopwatch.Elapsed.TotalMilliseconds));
        return result;
    }
}

public class Arithmatic
{
    private ILogger _log;
    public Arithmatic(ILogger log)//Inject Dependency
    {
        _log = log;
    }

    public void Calculate(int a, int b)
    {
        try
        {
            Console.WriteLine(Helper.Time(() => AddNumber(a, b), _log));//Return the result and do execution time logging
            Console.WriteLine(Helper.Time(() => SubtractNumber(a, b), _log));//Return the result and do execution time logging
        }
        catch (Exception ex)
        {
            _log.Error(ex.Message, ex);
        }
    }

    private string AddNumber(int a, int b)
    {
        return "Sum is:" + (a + b);
    }

    private string SubtractNumber(int a, int b)
    {
        return "Subtraction is:" + (a - b);
    }
}

public class Log : ILogger
{
    public void Info(string message)
    {
        Console.WriteLine(message);
    }

    public void Error(string message, Exception ex)
    {
        Console.WriteLine("Error Message:" + message, "Stacktrace:" + ex.StackTrace);
    }
}

public interface ILogger
{
    void Info(string message);
    void Error(string message, Exception ex);
}

Calling Part:

 static void Main()
 {
    ILogger log = new Log();
    Arithmatic obj = new Arithmatic(log);
    obj.Calculate(10, 3);
    Console.ReadLine();
 }

Solution 10 - C#

record the time when current step begins to process

DateTime dtStart = DateTime.Now;

//Calculate the total number of milliseconds request took (Timespan = to represent the time interval)-> current - started time stamp ...
//TotalMilliseconds -->Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds.
// to measure how long a function is running 
var result=((TimeSpan)(DateTime.Now - dtStart)).TotalMilliseconds.ToString("#,##0.00") + "ms";

Solution 11 - C#

To view elapsed milliseconds betweeen breakpoints when debugging code, Visual Studio provides PerfTips, it's a built-in, useful and fast tool.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsebastian.roibuView Question on Stackoverflow
Solution 1 - C#OmarView Answer on Stackoverflow
Solution 2 - C#OdedView Answer on Stackoverflow
Solution 3 - C#AlainView Answer on Stackoverflow
Solution 4 - C#EmilView Answer on Stackoverflow
Solution 5 - C#james lewisView Answer on Stackoverflow
Solution 6 - C#Nikhil AgrawalView Answer on Stackoverflow
Solution 7 - C#Matt BurlandView Answer on Stackoverflow
Solution 8 - C#PhilippeView Answer on Stackoverflow
Solution 9 - C#Sumit DeshpandeView Answer on Stackoverflow
Solution 10 - C#Harshit GuptaView Answer on Stackoverflow
Solution 11 - C#yu yang JianView Answer on Stackoverflow