C# 计算方法的执行时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14019510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:25:26  来源:igfitidea点击:

Calculate the execution time of a method

c#.nettimeriostopwatch

提问by Mahdi Tahsildari

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.

我有一个 I/O 计时方法,可以将数据从一个位置复制到另一个位置。计算执行时间的最佳和最真实的方法是什么?Thread? Timer? Stopwatch? 还有其他解决办法吗?我想要最准确、尽可能简短的。

采纳答案by Darin Dimitrov

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

Stopwatch专为此目的而设计,是在 .NET 中测量时间执行的最佳方法之一。

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

Do notuse DateTimeto measure time execution in .NET.

不要使用 DateTime来测量 .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 answercontains a nice overview.

正如@series0ne 在评论部分指出的那样:如果您想要真正精确地测量某些代码的执行情况,则必须使用操作系统内置的性能计数器。在以下的答案必须包含一个很好的概述。

回答by Jeff Foster

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

如果您有兴趣了解性能,最好的答案是使用分析器。

Otherwise, System.Diagnostics.StopWatchprovides a high resolution timer.

否则,System.Diagnostics.StopWatch提供高分辨率计时器。

回答by Soner G?nül

StopWatchclass looks for your best solution.

StopWatchclass 寻找您的最佳解决方案。

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.

它还有一个名为Stopwatch.IsHighResolution. 当然,这是硬件和操作系统的问题。

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

指示计时器是否基于高分辨率性能计数器。

回答by Brian Agnew

StopWatchwill 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.

秒表通过计算底层计时器机制中的计时器滴答来测量经过的时间。如果安装的硬件和操作系统支持高分辨率性能计数器,则 Stopwatch 类使用该计数器来测量经过的时间。否则,秒表类使用系统计时器来测量经过的时间。使用 Frequency 和 IsHighResolution 字段来确定秒表计时实现的精度和分辨率。

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.

如果您正在测量 IO,那么您的数字可能会受到外部事件的影响,我会非常担心。准确性(正如您在上面指出的那样)。相反,我会进行一系列测量并考虑这些数字的平均值和分布。

回答by Matthew Layton

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

从个人的经验来看,System.Diagnostics.Stopwatch类可以用来测量方法的执行时间,但是当心:这是不完全准确!

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?"

现在你想知道; “好吧,为什么第一次需要 132 毫秒,而其余时间明显更少?”

The answer is that Stopwatchdoes 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.

答案是Stopwatch它不能补偿 .NET 中的“背景噪声”活动,例如 JITing。因此,第一次运行您的方法时,首先是 .NET JIT。执行此操作所需的时间会添加到执行时间中。同样,其他因素也会导致执行时间发生变化。

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

RedGate ANTS Performance Profiler 是一种商业产品,但产生的结果非常准确。-使用 .NET 分析提高应用程序的性能

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

这是一篇关于分析的 StackOverflow 文章: -什么是好的 .NET 分析器?

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

我还写了一篇关于使用秒表进行性能分析的文章,您可能想看看 - .NET 中的性能分析

回答by 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);
   }
 }