34

我想对我的代码进行一些基本的分析,但发现 C# 中的 DateTime.Now 只有大约 16 毫秒的分辨率。我还没有找到更好的计时结构。

4

4 回答 4

55

这是一个用于计时操作的示例代码:

Dim sw As New Stopwatch()
sw.Start()
//Insert Code To Time
sw.Stop()
Dim ms As Long = sw.ElapsedMilliseconds
Console.WriteLine("Total Seconds Elapsed: " & ms / 1000)

编辑:

巧妙的是,它也可以恢复。

Stopwatch sw = new Stopwatch();
foreach(MyStuff stuff in _listOfMyStuff)
{
    sw.Start();
    stuff.DoCoolCalculation();
    sw.Stop();
}
Console.WriteLine("Total calculation time: {0}", sw.Elapsed);

System.Diagnostics.Stopwatch类将使用高分辨率计数器(如果您的系统上有可用的计数器)。

于 2008-10-02T15:43:21.643 回答
20

System.Diagnostics.StopWatch 类非常适合进行分析。

如果您不想编写自己的测量函数,这里是Vance Morrison 的代码计时器博客的链接。

于 2008-10-02T15:31:12.593 回答
8

对于最高分辨率的性能计数器,您可以使用底层的 win32 性能计数器。

添加以下 P/Invoke 信号:

[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
public static extern bool QueryPerformanceCounter(out long perfcount);

[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
public static extern bool QueryPerformanceFrequency(out long freq);

并使用以下方式调用他们:

#region Query Performance Counter
/// <summary>
/// Gets the current 'Ticks' on the performance counter
/// </summary>
/// <returns>Long indicating the number of ticks on the performance counter</returns>
public static long QueryPerformanceCounter()
{
    long perfcount;
    QueryPerformanceCounter(out perfcount);
    return perfcount;
}
#endregion

#region Query Performance Frequency
/// <summary>
/// Gets the number of performance counter ticks that occur every second
/// </summary>
/// <returns>The number of performance counter ticks that occur every second</returns>
public static long QueryPerformanceFrequency()
{
    long freq;
    QueryPerformanceFrequency(out freq);
    return freq;
}
#endregion

将其全部转储到一个简单的类中,您就可以开始了。示例(假设类名为 PerformanceCounters):

long startCount = PerformanceCounter.QueryPerformanceCounter();
// DoStuff();
long stopCount = PerformanceCounter.QueryPerformanceCounter();
long elapsedCount = stopCount - startCount;
double elapsedSeconds = (double)elapsedCount / PerformanceCounter.QueryPerformanceFrequency();
MessageBox.Show(String.Format("Took {0} Seconds", Math.Round(elapsedSeconds, 6).ToString()));
于 2008-10-02T15:48:37.467 回答
1

您可以调用 Windows 中的高分辨率性能计数器。函数名称为 kernel32.dll 中的 QueryPerformanceCounter。

导入 C# 的语法:

[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

Windows 调用的语法:

BOOL QueryPerformanceCounter(      
    LARGE_INTEGER *lpPerformanceCount
);

查询性能计数器@MSDN

于 2008-10-02T15:42:31.070 回答