Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I measure how long a function is running?

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?

like image 542
sebastian.roibu Avatar asked Apr 11 '12 13:04

sebastian.roibu


People also ask

How do I find out how long a program is running?

The simplest and most intuitive way to measure time is to use a stopwatch manually from the moment you start a program. Assuming you manage to start the stopwatch and the program at the same time, the option requires the program to print a certain warning at the end of execution or at the end of a subroutine.

How do you calculate time in a function in Python?

The timeit() method of the timeit module can also be used to calculate the execution time of any program in python. The timeit() method accepts four arguments. Let's see what are these arguments: setup, which takes the code which runs before the execution of the main program, the default value is pass.

How do you calculate time in a function in C++?

measure execution time of a program. Using time() function in C & C++. time() : time() function returns the time since the Epoch(jan 1 1970) in seconds. Prototype / Syntax : time_t time(time_t *tloc);


11 Answers

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);
like image 147
Omar Avatar answered Oct 08 '22 09:10

Omar


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
like image 44
Oded Avatar answered Oct 08 '22 09:10

Oded


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.

like image 43
Emil Avatar answered Oct 08 '22 10:10

Emil


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.

like image 41
Alain Avatar answered Oct 08 '22 11:10

Alain


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"));
like image 31
james lewis Avatar answered Oct 08 '22 11:10

james lewis


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);
}
like image 40
Nikhil Agrawal Avatar answered Oct 08 '22 11:10

Nikhil Agrawal


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.

like image 29
Matt Burland Avatar answered Oct 08 '22 11:10

Matt Burland


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();
});
like image 32
Philippe Avatar answered Oct 08 '22 11:10

Philippe


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();
 }
like image 27
Sumit Deshpande Avatar answered Oct 08 '22 09:10

Sumit Deshpande


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";
like image 38
Harshit Gupta Avatar answered Oct 08 '22 10:10

Harshit Gupta


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

like image 41
yu yang Jian Avatar answered Oct 08 '22 09:10

yu yang Jian