.NET/C# 在代码中测量代码执行耗时的建议(比较系统性能计数器和系统时间)


我们有很多种方法评估一个方法的执行耗时,比如使用性能分析工具,使用基准性能测试。不过传统的在代码中编写计时的方式依然有效,因为它可以生产环境或用户端得到真实环境下的执行耗时。

如果你希望在 .NET/C# 代码中编写计时,那么阅读本文可以获得一些建议。阅读本文也可以了解到 QueryPerformanceCounterGet-System-Time-As-File-Time 等方法的差异。


本文内容

      • 基本的计时
      • 结论:使用什么方法计时
      • 各种计时 API 及其比较
        • 基于系统性能计数器(QPC)的 API
        • 基于系统时间的 API
        • 基于 QPC 和系统时间的 API
        • 参考资料

C# 标准性能测试 - 林德熙
  • C# 标准性能测试高级用法 - 林德熙
  • The Old New Thing 一书中说,基于系统时间的 API 获取的时间戳精度用的是 “所谓的 Precise”,但实际上应该称之为 “Accurate”,而 QPC 才能称之为实质上的 “Precise”。纠结起来就是 QPC 比基于系统时间的 API 得到的时间戳精度更高。

    Acquiring high-resolution time stamps - Microsoft Docs
  • How accurate are the various Windows time-querying functions? – The Old New Thing
  • windows平台时间函数性能比较QueryPerformanceCounter,GetTickCount,ftime,time,GetLocalTime,GetSystemTimeAsFileTime - 小 楼 一 夜 听 春 雨 - 博客园
  • c# - Is DateTime.Now the best way to measure a function’s performance? - Stack Overflow
  • c# - How do I measure how long a function is running? - Stack Overflow
  • c# - Calculate the execution time of a method - Stack Overflow
  • Stopwatch.IsHighResolution Field (System.Diagnostics) - Microsoft Docs
  • Stopwatch.cs
  • timespan.cs