当前位置:  开发笔记 > 编程语言 > 正文

.NET中的高分辨率计时器

如何解决《.NET中的高分辨率计时器》经验,为你挑选了3个好方法。

我想对我的代码进行一些基本的分析,但发现C#中的DateTime.Now只有大约16毫秒的分辨率.必须有更好的时间保留我尚未找到的构造.



1> quickcel..:

以下是为操作计时的示例代码:

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类将使用它.



2> MagicKat..:

System.Diagnostics.StopWatch类非常适合分析.

如果您不想编写自己的测量功能,可以链接到Vance Morrison的代码计时器博客.



3> Wolfwyrd..:

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

添加以下P/Invoke sigs:

[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
/// 
/// Gets the current 'Ticks' on the performance counter
/// 
/// Long indicating the number of ticks on the performance counter
public static long QueryPerformanceCounter()
{
    long perfcount;
    QueryPerformanceCounter(out perfcount);
    return perfcount;
}
#endregion

#region Query Performance Frequency
/// 
/// Gets the number of performance counter ticks that occur every second
/// 
/// The number of performance counter ticks that occur every second
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()));


从.NET 2.0开始,Stopwatch类为您完成此操作.
推荐阅读
mobiledu2402852413
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有