高精度计时器(编程测试效率用)

高精度计时器(编程测试效率用)

1.HiPerfTimer.cs

using System; using System.Runtime.InteropServices; using System.ComponentModel; using System.Threading; namespace StringHelperTest { /// <summary> /// 高精度计时器 /// </summary> public class HiPerfTimer { [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceCounter(out long lpPerformanceCount); [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceFrequency(out long lpFrequency); private long startTime, stopTime; private long freq; /// <summary> /// 构造高精度计时器 /// </summary> public HiPerfTimer() { startTime = 0; stopTime = 0; if (QueryPerformanceFrequency(out freq) == false) { throw new Win32Exception(); } } /// <summary> /// 开始计时器 /// </summary> public void Start() { Thread.Sleep(0); QueryPerformanceCounter(out startTime); } /// <summary> /// 停止计时器 /// </summary> public void Stop() { QueryPerformanceCounter(out stopTime); } /// <summary> /// 返回执行周期 /// </summary> public double Duration { get { return (double)(stopTime – startTime) / (double) freq; } } } }

 

2.使用

HiPerfTimer time = new HiPerfTimer(); time.Start(); //执行代码… time.Stop(); Console.WriteLine(time.Duration);//输出耗时

 

 

 

转载于:https://www.cnblogs.com/TangZhongxin/archive/2009/07/31/3942565.html

Published by

风君子

独自遨游何稽首 揭天掀地慰生平