计算方法的执行时间

问题描述:

可能的重复:
如何衡量函数运行的时间?

我有一个 I/O 计时方法,可以将数据从一个位置复制到另一个位置.计算执行时间的最佳和最真实的方法是什么?线程?定时器?秒表?还有其他解决方案吗?我想要最准确的,尽可能简短的.

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.

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

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;

不要 使用 DateTime 测量 .NET 中的时间执行.

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

更新:

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

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.