VC中几个关于时间计算的函数

#include <iostream.h>
#include <windows.h>
#include <stdio.h>
#include <time.h>
void sleep( clock_t wait )
{
   clock_t goal;
   goal = wait + clock();
   while( goal > clock() )
      ;
}
int main()
{
	// 利用QueryPerformanceFrequency 和QueryPerformanceCounter 精确计算时间

	LARGE_INTEGER litmp;                 
	LONGLONG   QPart1,QPart2;  
    QueryPerformanceFrequency(&litmp);    // 获得CPU的频率
    double dfMinus,dfFreq,dfTim;     

	//   获得计数器的时钟频率     
	dfFreq = (double)litmp.QuadPart;
	cout<< "频率为:"<< dfFreq/1000000  <<"MHZ"<<endl;    
    
	QueryPerformanceCounter(&litmp);     
    
	//   获得初始值     
    
	QPart1 = litmp.QuadPart;
	cout<<double(QPart1)<<endl;  
	///  放入被测程序
	Sleep(100);     
    //  结束被测程序
	QueryPerformanceCounter(&litmp);     
    
	//   获得终止值     
    
	QPart2   =   litmp.QuadPart;

	cout<<double(QPart2)<<endl;    
    
	dfMinus   = (double)(QPart2-QPart1);     
	dfTim   =   dfMinus   /   dfFreq;     
	//   获得对应的时间值  
	cout<< "cost time is :"<< dfTim*1000000 << " us "<<endl;
	//CString s;
	Format("my name is %6s","wind");
	printf("%6.f",dfTim);
	cout<<endl;


	/******************* use clock *************************************************/
	cout<< "*************use clock get the time************"<<endl;


	clock_t start, finish;
	long    i = 600000L;

	start = clock();
	while( i-- );
	finish = clock();
	cout<< "Time is:" <<  (double)(finish - start)/CLOCKS_PER_SEC <<endl;     //只能精确到ms级 


	/************************* use gettickgount()**********************************/

	DWORD start_time = GetTickCount();
	
	sleep( (clock_t)3 * CLOCKS_PER_SEC );

	DWORD end_time = GetTickCount();

	cout<< end_time-start_time <<endl;                // 精确到ms

	return 0;
}

你可能感兴趣的:(VC中几个关于时间计算的函数)