看了这篇文章,
http://www.codeproject.com/Articles/2635/High-Performance-Timer-in-C
很不错的方法,虽然平时很少用到这么精确的定时器,但是这里我产生了一个想法,可以使用这个定时器,
用途:
1、 验证算法(code)执行的效率(时间上)
2、用于某些控制场合,比如需要对精确的时间周期
high-performance timer class:
/// <summary> /// A C# class to provide exact time measurement in your applications. /// craigtao : 可以用来验证算法的效率如何 /// </summary> internal 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; public HiPerfTimer() { startTime = 0; stopTime = 0; if (QueryPerformanceFrequency(out freq) == false) { // high-PerformanceFrequency counter not supported throw new Win32Exception(); } } //start the timer public void Start() { //lets do the waiting threads there work Thread.Sleep(0); QueryPerformanceCounter(out startTime); } //stop the timer public void Stop() { QueryPerformanceCounter(out stopTime); } //return the dutation of the timer (seconds) public double Duration { get { return (double)(stopTime - startTime) / (double)freq; } } }
测试使用:
class Program { static void Main(string[] args) { HiPerfTimer pt = new HiPerfTimer(); // create a new PerfTimer object pt.Start(); //the code time Console.WriteLine("Jesus loves you!\n"); Console.WriteLine("Jesus loves you!, you know? \n"); pt.Stop(); Console.WriteLine("Duration:{0} sec\n", pt.Duration); Console.ReadKey(); // for remain console windows } }
效果:
时间: 2024-10-10 02:30:41