C# 用法:
public static class QueryPerformanceMethd
{
[DllImport("kernel32.dll")]
public extern static short QueryPerformanceCounter(ref long x); [DllImport("kernel32.dll")]
public extern static short QueryPerformanceFrequency(ref long x);
}
static void Main(string[] args)
{
long stop_Value = 0;
long start_Value = 0;
long freq = 0; QueryPerformanceMethd.QueryPerformanceFrequency(ref freq);
QueryPerformanceMethd.QueryPerformanceCounter(ref start_Value);
//Fun() 需要计时方法
QueryPerformanceMethd.QueryPerformanceCounter(ref stop_Value);
double time = (double)(stop_Value - start_Value) / (double)(freq); Console.WriteLine(time);//单位S
Console.ReadLine();
}
计算所得time即为fun()方法所消耗时间。
C++中QueryPerformanceCounter QueryPerformanceFrequency的用法
#include "stdafx.h"
#include "windows.h" void main()
{
LARGE_INTEGER nFreq;
LARGE_INTEGER nBeginTime;
LARGE_INTEGER nEndTime;
double time;
QueryPerformanceFrequency(&nFreq);
QueryPerformanceCounter(&nBeginTime);
Sleep();
QueryPerformanceCounter(&nEndTime);
time = (double)(nEndTime.QuadPart - nBeginTime.QuadPart) / (double)nFreq.QuadPart;
printf("%f\n", time);
system("Pause");
}
计算Sleep(1000)所消耗的精确时间,并非精确的1s