代码改变世界

用于计时的两个Api函数

2005-12-13 22:20  Orin  阅读(517)  评论(1编辑  收藏  举报
今天在速马的Blog上看到了两个用于计时的Windows Api, 计时单位达到十亿分之一秒!

 

[DllImport("Kernel32.dll")]
static extern bool QueryPerformanceCounter([In, Out] long lpPerformanceCount);
[DllImport(
"Kernel32.dll")]
static extern bool QueryPerformanceFrequency([In, Out] long lpFrequency);

速马将其封装成了类,感谢速马!

 

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

public class StopWatch
{
 [DllImport(
"Kernel32.dll")]
 
static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

 [DllImport(
"Kernel32.dll")]
 
static extern bool QueryPerformanceFrequency(out long lpFrequency);

 
long start;
 
long stop;
 
long frequency;
 
const decimal multiplier = 1.0e9M;

 
public StopWatch()
 
{
  
if (QueryPerformanceFrequency(out frequency) == false)
  
{
   
// Frequency not supported
   throw new Win32Exception();
  }

 }


 
public void Start()
 
{
  QueryPerformanceCounter(
out start);
 }


 
public void Stop()
 
{
  QueryPerformanceCounter(
out stop);
 }


 
public double Duration(int iterations)
 
{
  
return ((((double)(stop - start) * (double)multiplier) / (double)frequency) / iterations);
 }

}

 

它的使用很简单,如下所示:

StopWatch myTimer = new StopWatch();
// Measure without boxing
myTimer.Start();
for(int i = 0; i < iterations; i++)
{
  
// do some work to time
}

myTimer.Stop();
// 计算每次循环所花的平均时间(单位:十亿分之一秒)
double result = myTimer.Duration(iterations);