首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >.NET中的高精度定时器

.NET中的高精度定时器
EN

Stack Overflow用户
提问于 2008-10-02 15:30:14
回答 4查看 20.6K关注 0票数 34

我想对我的代码做一些基本的分析,但发现C#中的DateTime.Now只有大约16ms的分辨率。一定有更好的时间来保存我还没有发现的构造。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2008-10-02 15:43:22

下面是对操作计时的示例代码:

代码语言:javascript
复制
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)

编辑:

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

代码语言:javascript
复制
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类将使用高分辨率计数器。

票数 55
EN

Stack Overflow用户

发布于 2008-10-02 15:31:13

System.Diagnostics.StopWatch类对于性能分析来说非常棒。

如果您不想编写自己的度量函数,这里有一个指向Vance Morrison's Code Timer Blog的链接。

票数 20
EN

Stack Overflow用户

发布于 2008-10-02 15:48:37

对于最高分辨率性能计数器,可以使用基础win32性能计数器。

添加以下P/Invoke符号:

代码语言:javascript
复制
[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);

并使用以下命令调用它们:

代码语言:javascript
复制
#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):

代码语言:javascript
复制
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()));
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/163022

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档