486
votes

I need to find a bottleneck and need to accurately as possible measure time.

Is the following code snippet the best way to measure the performance?

DateTime startTime = DateTime.Now;

// Some execution process

DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);
16
By the way, if you are not looking for something quick and dirty performance counters can be used.Jonathan C Dickinson
If you need greater precision use Stopwatch.GetTimestamp, otherwise the answer is good.dbasnett
@dbasnett Can you go into more detail in an answer?David Basarab
In the above example change start and endtime to long and assign Stopwatch.GetTimestamp to them instead of DateTime.Now. The time taken is (end-start)/Stopwatch.Frequency.dbasnett
"Best" is subjective. This question needs to define what is meant by "best" in an objective way.Heretic Monkey

16 Answers

663
votes

No, it's not. Use the Stopwatch (in System.Diagnostics)

Stopwatch sw = Stopwatch.StartNew();
PerformWork();
sw.Stop();

Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);

Stopwatch automatically checks for the existence of high-precision timers.

It is worth mentioning that DateTime.Now often is quite a bit slower than DateTime.UtcNow due to the work that has to be done with timezones, DST and such.

DateTime.UtcNow typically has a resolution of 15 ms. See John Chapman's blog post about DateTime.Now precision for a great summary.

Interesting trivia: The stopwatch falls back on DateTime.UtcNow if your hardware doesn't support a high frequency counter. You can check to see if Stopwatch uses hardware to achieve high precision by looking at the static field Stopwatch.IsHighResolution.

94
votes

If you want something quick and dirty I would suggest using Stopwatch instead for a greater degree of precision.

Stopwatch sw = new Stopwatch();
sw.Start();
// Do Work
sw.Stop();

Console.WriteLine("Elapsed time: {0}", sw.Elapsed.TotalMilliseconds);

Alternatively, if you need something a little more sophisticated you should probably consider using a 3rd party profiler such as ANTS.

60
votes

This article says that first of all you need to compare three alternatives, Stopwatch, DateTime.Now AND DateTime.UtcNow.

It also shows that in some cases (when performance counter doesn't exist) Stopwatch is using DateTime.UtcNow + some extra processing. Because of that it's obvious that in that case DateTime.UtcNow is the best option (because other use it + some processing)

However, as it turns out, the counter almost always exists - see Explanation about high-resolution performance counter and its existence related to .NET Stopwatch?.

Here is a performance graph. Notice how low performance cost UtcNow has compared to alternatives:

Enter image description here

The X axis is sample data size, and the Y axis is the relative time of the example.

One thing Stopwatch is better at is that it provides higher resolution time measurements. Another is its more OO nature. However, creating an OO wrapper around UtcNow can't be hard.

19
votes

It's useful to push your benchmarking code into a utility class/method. The StopWatch class does not need to be Disposed or Stopped on error. So, the simplest code to time some action is

public partial class With
{
    public static long Benchmark(Action action)
    {
        var stopwatch = Stopwatch.StartNew();
        action();
        stopwatch.Stop();
        return stopwatch.ElapsedMilliseconds;
    }
}

Sample calling code

public void Execute(Action action)
{
    var time = With.Benchmark(action);
    log.DebugFormat(“Did action in {0} ms.”, time);
}

Here is the extension method version

public static class Extensions
{
    public static long Benchmark(this Action action)
    {
        return With.Benchmark(action);
    }
}

And sample calling code

public void Execute(Action action)
{
    var time = action.Benchmark()
    log.DebugFormat(“Did action in {0} ms.”, time);
}
17
votes

The stopwatch functionality would be better (higher precision). I'd also recommend just downloading one of the popular profilers, though (DotTrace and ANTS are the ones I've used the most... the free trial for DotTrace is fully functional and doesn't nag like some of the others).

14
votes

Use the System.Diagnostics.Stopwatch class.

Stopwatch sw = new Stopwatch();
sw.Start();

// Do some code.

sw.Stop();

// sw.ElapsedMilliseconds = the time your "do some code" took.
11
votes

Ditto Stopwatch, it is way better.

Regarding performance measuring you should also check whether your "// Some Execution Process" is a very short process.

Also bear in mind that the first run of your "// Some Execution Process" might be way slower than subsequent runs.

I typically test a method by running it 1000 times or 1000000 times in a loop and I get much more accurate data than running it once.

9
votes

These are all great ways to measure time, but that is only a very indirect way to find bottleneck(s).

The most direct way to find a bottneck in a thread is to get it running, and while it is doing whatever makes you wait, halt it with a pause or break key. Do this several times. If your bottleneck takes X% of time, X% is the probability that you will catch it in the act on each snapshot.

Here's a more complete explanation of how and why it works

7
votes

@Sean Chambers

FYI, the .NET Timer class is not for diagnostics, it generates events at a preset interval, like this (from MSDN):

System.Timers.Timer aTimer;
public static void Main()
{
    // Create a timer with a ten second interval.
    aTimer = new System.Timers.Timer(10000);

    // Hook up the Elapsed event for the timer.
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

    // Set the Interval to 2 seconds (2000 milliseconds).
    aTimer.Interval = 2000;
    aTimer.Enabled = true;

    Console.WriteLine("Press the Enter key to exit the program.");
    Console.ReadLine();
}

// Specify what you want to happen when the Elapsed event is 
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}

So this really doesn't help you know how long something took, just that a certain amount of time has passed.

The timer is also exposed as a control in System.Windows.Forms... you can find it in your designer tool box in VS05/VS08

7
votes

This is the correct way:

using System;
using System.Diagnostics;

class Program
{
    public static void Main()
    {
        Stopwatch stopWatch = Stopwatch.StartNew();

            // some other code

        stopWatch.Stop();

        // this not correct to get full timer resolution
        Console.WriteLine("{0} ms", stopWatch.ElapsedMilliseconds);

        // Correct way to get accurate high precision timing
        Console.WriteLine("{0} ms", stopWatch.Elapsed.TotalMilliseconds);
    }
}

For more information go through Use Stopwatch instead of DataTime for getting accurate performance counter.

6
votes

Visual Studio Team System has some features that may help with this problem. Essentially you can write unit tests and mix them in different scenarios to run against your software as part of a stress or load test. This may help to identify areas of code that impact your applications performance the most.

Microsoft' Patterns and Practices group has some guidance in Visual Studio Team System Performance Testing Guidance.

5
votes

I just found a post in Vance Morrison's blog about a CodeTimer class he wrote that makes using StopWatch easier and does some neat stuff on the side.

5
votes

The way I use within my programs is using the StopWatch class as shown here.

Stopwatch sw = new Stopwatch();
sw.Start();


// Critical lines of code

long elapsedMs = sw.Elapsed.TotalMilliseconds;
5
votes

This is not professional enough:

Stopwatch sw = Stopwatch.StartNew();
PerformWork();
sw.Stop();

Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);

A more reliable version is:

PerformWork();

int repeat = 1000;

Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < repeat; i++)
{
   PerformWork();
}

sw.Stop();

Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds / repeat);

In my real code, I will add GC.Collect call to change managed heap to a known state, and add Sleep call so that different intervals of code can be easily separated in ETW profile.

4
votes

I've done very little of this sort of performance checking (I tend to just think "this is slow, make it faster") so I have pretty much always gone with this.

A google does reveal a lot of resources/articles for performance checking.

Many mention using pinvoke to get performance information. A lot of the materials I study only really mention using perfmon..

Edit:

Seen the talks of StopWatch.. Nice! I have learned something :)

This looks like a good article

0
votes

Since I do not care to much about precision I ended up comparing them. I am capturing lots of packets on the network and I want to place the time when I receive each packet. Here is the code that tests 5 million iterations

    int iterations = 5000000;

    // Test using datetime.now
    {
        var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);

        var now = DateTime.UtcNow;

        for (int i = 0; i < iterations; i++)
        {
            if (date == DateTime.Now)
                Console.WriteLine("it is!");
        }
        Console.WriteLine($"Done executing {iterations} iterations using datetime.now. It took {(DateTime.UtcNow - now).TotalSeconds} seconds");
    }

    // Test using datetime.utcnow
    {
        var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);

        var now = DateTime.UtcNow;

        for (int i = 0; i < iterations; i++)
        {
            if (date == DateTime.UtcNow)
                Console.WriteLine("it is!");
        }
        Console.WriteLine($"Done executing {iterations} iterations using datetime.utcnow. It took {(DateTime.UtcNow - now).TotalSeconds} seconds");
    }

    // Test using stopwatch
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        var now = DateTime.UtcNow;

        for (int i = 0; i < iterations; i++)
        {
            if (sw.ElapsedTicks == DateTime.Now.Ticks)
                Console.WriteLine("it is!");
        }
        Console.WriteLine($"Done executing {iterations} iterations using stopwatch. It took {(DateTime.UtcNow - now).TotalSeconds} seconds");
    }

The output is:

Done executing 5000000 iterations using datetime.now. It took 0.8685502 seconds 
Done executing 5000000 iterations using datetime.utcnow. It took 0.1074324 seconds 
Done executing 5000000 iterations using stopwatch. It took 0.9625021 seconds

So in conclusion DateTime.UtcNow is the fastest if you do not care to much about precision. This also supports the answer https://stackoverflow.com/a/6986472/637142 from this question.