vc 程序效率测试 与 如何获取系统精确时间

                GetTickCount返回(retrieve)从操作系统启动到现在所经过(elapsed)的毫秒数,它的返回值是DWORD。


如: DWORD time;

       time = GetTickCount();

但是

GetTickcount函数:它返回从 操作系统启动到当前所经过的毫秒数,常常用来判断某个方法执行的时间,其函数原型是DWORD GetTickCount(void),返回值以32位的双字类型DWORD存储,因此可以存储的最大值是2^32 ms约为49.71天,因此若系统运行时间超过49.71天时,这个数就会归0, MSDN中也明确的提到了:"Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days."。因此,如果是编写 服务器端程序,此处一定要万分注意,避免引起意外的状况。
特别注意:这个函数并非实时发送,而是由系统每18ms发送一次,因此其最小精度为18ms。当需要有小于18ms的精度计算时,应使用StopWatch方法进行。也就是说使用这个函数,精度不高。
为了获取精确的时间,从而获得精确的效率测量可以使用 QueryPerformanceCounter(&ticks)函数
示例程序可以这样用:
   ////////////variables definition////////////
	 DWORD time1,time2,time3;//计算时间用
	  LARGE_INTEGER  frequency;//高性能计数器的频率
	 LARGE_INTEGER start,end;
	 start.QuadPart=0;
	 end.QuadPart=0;
	 frequency.QuadPart=0;
	 long ticks=0;
	 QueryPerformanceFrequency(&frequency);
///////////////////processing ///////////
	#ifdef DEBUGTIME
	 time1 = GetTickCount();
	 QueryPerformanceCounter(&start);
    #endif
#ifdef DEBUGTIME
	 time2 = GetTickCount();
	 QueryPerformanceCounter(&end);
     ticks = (long)(end.QuadPart-start.QuadPart);
	 double millsecond=(double)ticks*1000.0/(double)frequency.QuadPart;
	 printf("noninterpolating wasted time is %ld  number %ld  ticks %lf\n",time2-time1,arrayindex,millsecond);
#endif

这是一位名叫 softman11,csdn论坛里这位作者提供的c++ 类实现
#pragma once
#include<Windows.h>
 
///本类采用高分辨率高性能计数器实现
///在我的Intel T7500机器上,分辨率大约是279毫微秒
class StopWatch
{
public:
    StopWatch(void);
    ~StopWatch(void);
private:
    LARGE_INTEGER beginticks;
    LARGE_INTEGER endticks ;
    LARGE_INTEGER  frequency;//高性能计数器的频率:每秒357,9545个tick  我的INTEL T7500
public:
    void Start();
    void Stop();
    double  GetCostMillisecond();
    unsigned long long  GetFrequency();
};
 
#include "StdAfx.h"
#include "StopWatch.h"
#include <Windows.h>
#include<iostream>
using namespace std;
 
StopWatch::StopWatch(void)
{
    beginticks.QuadPart=0;
    endticks.QuadPart=0;
    frequency.QuadPart=0;
    QueryPerformanceFrequency(&frequency);
}
 
 
StopWatch::~StopWatch(void)
{
}
 
void StopWatch::Start()
{
    //beginticks=GetTickCount();
    QueryPerformanceCounter(&beginticks);
     
}
void StopWatch::Stop()
{
    QueryPerformanceCounter(&endticks);
     
}
double  StopWatch::GetCostMillisecond()
{
    unsigned long long cost=(unsigned long long)(endticks.QuadPart-beginticks.QuadPart);
    double millsecond=(double)cost*1000.0/(double)frequency.QuadPart;    
    return millsecond;
}
unsigned long long StopWatch::GetFrequency()
{
    return (unsigned long long)frequency.QuadPart;
}



0
0
 
 

你可能感兴趣的:(C++,优化,C语言,VC,windbg)