Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring code execution time

People also ask

How is code execution time calculated?

We can calculate the execution time of the code using StartNew() and Stop() methods. StartNew() method comes under the Stopwatch class and it basically used to initialize a new Stopwatch instance. Internally it marks the elapsed time property equal to zero and then it starts measuring the elapsed time.

How does Python calculate code execution time?

Method 1: Using Timeit Module Python timeit module is often used to measure the execution time of small code snippets. We can also use the timeit() function which executes an anonymous function with a number of executions.

How does Visual Studio measure execution time?

If milliseconds then in Visual Studio 2019 you can see the time between two breakpoints under Diagnostic Tools -> Events -> Duration (opens automatically in Debug mode, or use Ctrl + Alt + F2 ).

How do you measure time in C++?

Since C++11, the best way to measure elapsed time in C++ is by using the Chrono library, which deals with time. Following C++ program calculates the time elapsed for a simple code in seconds, milliseconds, microseconds, and nanoseconds.


A better way would be to use Stopwatch, instead of DateTime differences.

Stopwatch Class - Microsoft Docs

Provides a set of methods and properties that you can use to accurately measure elapsed time.

// create and start a Stopwatch instance
Stopwatch stopwatch = Stopwatch.StartNew(); 

// replace with your sample code:
System.Threading.Thread.Sleep(500);

stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);

Stopwatch measures time elapsed.

// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();

// Begin timing
stopwatch.Start();

Threading.Thread.Sleep(500)

// Stop timing
stopwatch.Stop();

Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);

Here is a DEMO.


You can use this Stopwatch wrapper:

public class Benchmark : IDisposable 
{
    private readonly Stopwatch timer = new Stopwatch();
    private readonly string benchmarkName;

    public Benchmark(string benchmarkName)
    {
        this.benchmarkName = benchmarkName;
        timer.Start();
    }

    public void Dispose() 
    {
        timer.Stop();
        Console.WriteLine($"{benchmarkName} {timer.Elapsed}");
    }
}

Usage:

using (var bench = new Benchmark($"Insert {n} records:"))
{
    ... your code here
}

Output:

Insert 10 records: 00:00:00.0617594

For advanced scenarios, you can use BenchmarkDotNet or Benchmark.It or NBench


If you use the Stopwatch class, you can use the .StartNew() method to reset the watch to 0. So you don't have to call .Reset() followed by .Start(). Might come in handy.


If you are looking for the amount of time that the associated thread has spent running code inside the application.
You can use ProcessThread.UserProcessorTime Property which you can get under System.Diagnostics namespace.

TimeSpan startTime= Process.GetCurrentProcess().Threads[i].UserProcessorTime; // i being your thread number, make it 0 for main
//Write your function here
TimeSpan duration = Process.GetCurrentProcess().Threads[i].UserProcessorTime.Subtract(startTime);

Console.WriteLine($"Time caluclated by CurrentProcess method: {duration.TotalSeconds}"); // This syntax works only with C# 6.0 and above

Note: If you are using multi threads, you can calculate the time of each thread individually and sum it up for calculating the total duration.