ChatGPT解决这个技术问题 Extra ChatGPT

Calculate the execution time of a method

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.


M
Matthias Braun

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.


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.
@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.
@series0ne, very good point. I will update my answer to include your valuable comment.
@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?
@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.
M
Matthew Layton

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


@mahditahsildari No problem. Glad I could help! :-)
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.
@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.
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.
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.
S
Soner Gönül

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.


J
Jeff Foster

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

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


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
T
Tạ Lục Gia Hoàng

Following this Microsoft Doc:

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    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);
    }
}

Output: RunTime 00:00:09.94


B
Brian Agnew

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.


K
Khai Vu

You also use this, "Gets the number of milliseconds elapsed since the system started."

System.Environment.TickCount

For example

static void method1()
{
    for (int i = 1; i <= 100; i++)
    {
        Console.WriteLine("Test1 " + i);
    }
}
static void Main(string[] args)
{
    var startTime = Environment.TickCount;
    method1();
    var endTime = Environment.TickCount;
    Console.WriteLine("RunTime " + (endTime - startTime));
}

M
Md.Rakibuz Sultan
 using System.Diagnostics;
 class Program
 {
    static void Test1()
    {
        for (int i = 1; i <= 100; i++)
        {
            Console.WriteLine("Test1 " + i);
        }
    }
  static void Main(string[] args)
    {

        Stopwatch sw = new Stopwatch();
        sw.Start();
        Test1();
        sw.Stop();
        Console.WriteLine("Time Taken-->{0}",sw.ElapsedMilliseconds);
   }
 }