且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中测量执行时间

更新时间:2022-10-15 16:03:32

Stopwatch 类专门设计用于测量经过时间,在您的硬件上可用)使用基础的高频硬件定时器提供良好的粒度/精度。所以这似乎是***的选择。



IsHighResolution属性可用于确定高分辨率时序是否可用。根据文档,该类提供了***可用Win32 API的封装,以便精确计时:


具体来说,频率字段和
GetTimestamp 方法可用于
非托管Win32 API的位置
QueryPerformanceFrequency
QueryPerformanceCounter


有关这些Win32 API [这里]和链接的MSDN文档的详细背景 2


高分辨率计时器 / p>

一个计数器是用于
编程的通用术语,用于指代
递增变量。一些系统
包括一个高分辨率的性能
计数器,提供高分辨率
已经过去的时间。



如果高分辨率的性能
计数器存在于系统上,您可以
使用 QueryPerformanceFrequency
函数来表示频率,每秒
计数。
计数的值取决于处理器。在某些
处理器上,例如,
的计数可能是
处理器时钟的周期率。



QueryPerformanceCounter 功能
检索
高分辨率性能计数器的当前值。
通过在
开始和结束
代码的
调用此函数,应用程序基本上使用
计数器作为高分辨率
定时器。例如,假设
QueryPerformanceFrequency 表示

高分辨率性能计数器的频率为
每秒50,000个计数。如果
应用程序在
部分代码之前和之后立即
调用

,那么
计数器值可能是1500分别计算
和3500计数。这些
值将表示执行代码
时已经过了.04秒
(2000计数)。



I want to measure the execution of a piece of code and I'm wondering what the best method to do this is?

Option 1:

DateTime StartTime = DateTime.Now;

//Code

TimeSpan ts = DateTime.Now.Subtract(StartTime);
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
Console.WriteLine(elapsedTime, "RunTime");

Option 2: using System.Diagnostics;

    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();

    //Code

    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(elapsedTime, "RunTime");

This isn't simply for benchmarking, its actually part of the application. The time the function takes to execute is relevant data. It doesn't however need to be atomic or hyper-accurate.

Which option is better for production code, or does anybody else use something different and perhaps better?

The Stopwatch class is specifically designed to measure elapsed time and may (if available on your hardware) provide good granularity/accuracy using an underlying high-frequency hardware timer. So this seem the best choice.

The IsHighResolution property can be used to determine whether high resolution timing is available. Per the documentation, this class offers a wrapper on the 'best available' Win32 APIs for accurate timing:

Specifically, the Frequency field and GetTimestamp method can be used in place of the unmanaged Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter.

There is detailed background on those Win32 APIs [here] and in linked MSDN docs 2.

High-Resolution Timer

A counter is a general term used in programming to refer to an incrementing variable. Some systems include a high-resolution performance counter that provides high-resolution elapsed times.

If a high-resolution performance counter exists on the system, you can use the QueryPerformanceFrequency function to express the frequency, in counts per second. The value of the count is processor dependent. On some processors, for example, the count might be the cycle rate of the processor clock.

The QueryPerformanceCounter function retrieves the current value of the high-resolution performance counter. By calling this function at the beginning and end of a section of code, an application essentially uses the counter as a high-resolution timer. For example, suppose that QueryPerformanceFrequency indicates that the frequency of the high-resolution performance counter is 50,000 counts per second. If the application calls QueryPerformanceCounter immediately before and immediately after the section of code to be timed, the counter values might be 1500 counts and 3500 counts, respectively. These values would indicate that .04 seconds (2000 counts) elapsed while the code executed.