Calculate the execution time of a method

597,926

Solution 1

Stopwatch is designed for this purpose and is one of the best ways to measure time execution in .NET.

var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;

Do not use DateTime to measure time execution in .NET.


UPDATE:

As pointed out by @series0ne in the comments section: If you want a real precise measurement of the execution of some code, you will have to use the performance counters that's built into the operating system. The following answer contains a nice overview.

Solution 2

From personal experience, the System.Diagnostics.Stopwatch class can be used to measure the execution time of a method, however, BEWARE: It is not entirely accurate!

Consider the following example:

Stopwatch sw;

for(int index = 0; index < 10; index++)
{
    sw = Stopwatch.StartNew();
    DoSomething();
    Console.WriteLine(sw.ElapsedMilliseconds);
}

sw.Stop();

Example results

132ms
4ms
3ms
3ms
2ms
3ms
34ms
2ms
1ms
1ms

Now you're wondering; "well why did it take 132ms the first time, and significantly less the rest of the time?"

The answer is that Stopwatch does not compensate for "background noise" activity in .NET, such as JITing. Therefore the first time you run your method, .NET JIT's it first. The time it takes to do this is added to the time of the execution. Equally, other factors will also cause the execution time to vary.

What you should really be looking for absolute accuracy is Performance Profiling!

Take a look at the following:

RedGate ANTS Performance Profiler is a commercial product, but produces very accurate results. - Boost the performance of your applications with .NET profiling

Here is a StackOverflow article on profiling: - What Are Some Good .NET Profilers?

I have also written an article on Performance Profiling using Stopwatch that you may want to look at - Performance profiling in .NET

Solution 3

StopWatch class looks for your best solution.

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

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

Also it has a static field called Stopwatch.IsHighResolution. Of course, this is a hardware and operating system issue.

Indicates whether the timer is based on a high-resolution performance counter.

Solution 4

If you are interested in understand performance, the best answer is to use a profiler.

Otherwise, System.Diagnostics.StopWatch provides a high resolution timer.

Solution 5

StopWatch will use the high-resolution counter

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

If you're measuring IO then your figures will likely be impacted by external events, and I would worry so much re. exactness (as you've indicated above). Instead I'd take a range of measurements and consider the mean and distribution of those figures.

Share:
597,926
Mahdi Tahsildari
Author by

Mahdi Tahsildari

Love programming, it's fun. MCP since 2011. C#, ASP.net MVC Core, SQL; NodeJs, Angular, HTML, CSS, Javascript. Currently focused on ASP.Net Core and Unit Testing.

Updated on August 31, 2021

Comments

  • Mahdi Tahsildari
    Mahdi Tahsildari almost 3 years

    Possible Duplicate:
    How do I measure how long a function is running?

    I have an I/O time-taking method which copies data from a location to another. What's the best and most real way of calculating the execution time? Thread? Timer? Stopwatch? Any other solution? I want the most exact one, and briefest as much as possible.

  • Mahdi Tahsildari
    Mahdi Tahsildari over 11 years
    Exactly, and what about this case: i have a foreach loop that has a ThreadPool.QueueUserWorkItem(delegate { CopyFiles(folder, dest); }); inside, but stopwatch stops before everything is done.
  • Darin Dimitrov
    Darin Dimitrov over 11 years
    Then you should put your Stopwatch inside the delegate in order to measure the performance of the CopyFiles method.
  • Matthew Layton
    Matthew Layton over 11 years
    @DarinDimitrov - Stopwatch isn't entirely accurate? remember that .NET background noise (such as JITing) causes varying execution times to occur. Therefore, realistically, for accurate measurements, the OP should be using a performance profiler.
  • Matthew Layton
    Matthew Layton over 11 years
    Absolutely correct! I'm a little disheartened that so many on here have suggested using the Stopwatch, as it is not entirely accurate. However as you suggested using a Performance profiler, this is the correct way to do it! +1
  • Darin Dimitrov
    Darin Dimitrov over 11 years
    @series0ne, very good point. I will update my answer to include your valuable comment.
  • Mahdi Tahsildari
    Mahdi Tahsildari over 11 years
    Good point +1. Thanks for your accuracy, I accepted Darin's answer for the sake of simplicity, accuracy was in the second level of importance in this case.
  • Matthew Layton
    Matthew Layton over 11 years
    @mahditahsildari No problem. Glad I could help! :-)
  • Eric Lippert
    Eric Lippert over 11 years
    I'm not sure why this is an example of inaccuracy. The stopwatch is accurately measuring the total cost of the first call, which surely is what is relevant to the customer who is going to be running this code. They don't care whether those 132 milliseconds are charged to the method execution or to the jitter, they care about the total time elapsed.
  • Matthew Layton
    Matthew Layton over 11 years
    @EricLippert you raise a good point here, admittedly if the code is only going to be run once, then yes, JITing and various other "noise" will credibly factor into the result, however the OP (and indeed others) may have other scenarios, for example, the code may be executed in a loop, therefore you might calculate the average of all iterations, or require the longest/shortest execution time.
  • svick
    svick over 11 years
    @series0ne If you care about the performance of a loop, then measure the performance of a loop. Don't simply assume that doing something n times means it will be exactly n times slower as executing it once.
  • Matthew Layton
    Matthew Layton over 10 years
    @DarinDimitrov, I recently had an interview with a very skilled senior developer. He pointed out to me that using DateTimes is actually more accurate than using a StopWatch. He said the reason for this is that the Stopwatch in .NET does not take into account CPU affinity, and therefore, if your thread moves from one core to another, the StopWatch doesn't take into account the execution time across the other cores; only the one where the thread began execution. What is your opinion on this?
  • Darin Dimitrov
    Darin Dimitrov over 10 years
    @series0ne, what the senior developer told you about the Stopwatch and DateTime is absolutely true. Except that with DateTime you do not have enough accuracy. The problem is that there is no such class in .NET that would allow you all those features.
  • Matthew Layton
    Matthew Layton over 10 years
    @DarinDimitrov, I see. He also told me of a CPU affine StopWatch/Timer that someone had written and posted on public source sites (CodePlex/Code Project)...I've yet to find it!
  • Peter
    Peter about 7 years
    Besides that on average a PC is doing lots of things in the background, so stopwatch should not be taken too literal, but as an indication
  • ILIA BROUDNO
    ILIA BROUDNO over 6 years
    First off, the code sample should produce the output with ever-increasing number as StopWatch is never reset in the loop. And by "should" I mean it does (I checked). So your output does not match the code. Second, when I corrected the code to do a Stop/Write/Reset/Start in the loop, the first measurement was the same as the rest. My guess is your DoSomething does something for longer the first time it runs. JIT may or may not be the reason for it, but it's not that Stopwatch is affecting the measurement. Hence -1.
  • Matthew Layton
    Matthew Layton over 6 years
    @ILIABROUDNO did you notice that after 10 runs the program stops? You’ve obviously modified the code
  • Rui Miguel Pinheiro
    Rui Miguel Pinheiro over 5 years
    ILIA BROUDNO is absolutely correct, I got the same results. @series0ne, you have a Console.WriteLine inside the loop, writing the ms so far; because you only stop the watch AFTER the loop ends, it is increasing over time with each iteration, so we should see something like 3, 6, 10, 12, 15... as the time accumulates over the executions.
  • Matthew Layton
    Matthew Layton over 5 years
    @RuiMiguelPinheiro Yes, so I see. My latest update should put that right
  • Salman Arshad
    Salman Arshad about 4 years
    It always return 1.