C# 记录代码运行时间
时间: 2025-01-07 08:37:08 浏览: 55
### 计算 C# 中代码执行时间的方法
对于计算一段代码的执行时间,在 C# 中推荐使用 `Stopwatch` 类来实现这一功能[^1]。此工具提供了高分辨率的时间测量能力,能够提供较为精准的结果。
下面是一个简单的例子展示如何利用 `Stopwatch` 来度量一段用于文件拷贝操作的函数所花费的实际时间:
```csharp
using System;
using System.Diagnostics;
class Program {
static void Main(string[] args) {
string sourcePath = "source_file_path";
string destinationPath = "destination_file_path";
Stopwatch stopwatch = new Stopwatch();
// 开始计时
stopwatch.Start();
// 执行耗时的操作,比如复制文件
File.Copy(sourcePath, destinationPath, true);
// 停止计时
stopwatch.Stop();
Console.WriteLine($"File copy operation took {stopwatch.ElapsedMilliseconds} ms");
}
}
```
除了上述提到的方式外,还有其他几种可能的选择,但是它们各有优缺点。例如,可以通过多线程的方式来尝试并行化某些任务以减少整体等待时间;然而这通常不会直接影响单个任务本身的执行时间测量准确性。而如果考虑使用定时器(Timer),虽然也可以完成这项工作,但在精度上往往不如 `Stopwatch` 高,并且配置起来也更加复杂一些。
为了获得最精确且简洁的结果,建议采用 `Stopwatch` 方法来进行此类性能测试。
阅读全文
相关推荐



















