计时方法

简述:

讨论几种常用的记时方法。

包括精确到秒、毫秒、微秒的几种方法,供使用时候备忘


代码:

/***********************计时方式*********************/
//1 秒  = 1000毫秒 = 1000000微秒

#include <iostream>
#include <time.h>
#include <windows.h>

using namespace std;


int main(){
	//1. time_t 记录毫秒,使用<time.h>
	time_t time_start = time(NULL);
	Sleep(1000);
	time_t time_end = time(NULL);
	cout << "time_t 起始值: " << time_start << endl;
	cout << "time_t 终止值: " << time_end << endl;
	cout << "time_t显示 秒: " << time_end - time_start << "秒" << "\n\n";

	//2. clock_t 记录毫秒,使用<time.h>
	clock_t clock_start = clock();
	Sleep(1000);
	clock_t clock_end = clock();
	cout << "clock_t 起始值: " << clock_start << endl;
	cout << "clock_t 终止值: " << clock_end << endl;
	cout << "clock_t显示毫秒: " << clock_end - clock_start << "毫秒" << "\n\n";

	//用GetTickCount()来计时毫秒,使用#include <windows.h>
	DWORD  tickCount_start = GetTickCount();
	tickCount_start = GetTickCount();
	Sleep(1000);
	DWORD tickCount_end = GetTickCount();
	cout << "GetTickCount() 起始值: " << tickCount_start << endl;
	cout << "GetTickCount() 终止值: " << tickCount_end << endl;
	cout << "GetTickCount() 显示毫秒: " << tickCount_end - tickCount_start << "毫秒" << "\n\n";

	//用QueryPerformanceCounter()来计时微秒,使用#include <windows.h>
	LARGE_INTEGER  large_interger;
	double dff;
	__int64  c1, c2;
	QueryPerformanceFrequency(&large_interger);
	dff = large_interger.QuadPart;
	QueryPerformanceCounter(&large_interger);
	c1 = large_interger.QuadPart;
	Sleep(1000);
	QueryPerformanceCounter(&large_interger);
	c2 = large_interger.QuadPart;
	cout << "本机高精度计时器频率:" << dff << endl;
	cout << "第一次计时器值: " << c1 << endl;
	cout << "第二次计时器值: " << c2 << endl;
	cout << "计时器差: " << c2 - c1 << endl;
	cout << "QueryPerformanceCounter()显示微秒: " << (c2 - c1) * 1000 / dff << "微秒" << "\n\n";

	return 0;
}


测试输出:

time_t 起始值: 1340540074
time_t 终止值: 1340540075
time_t显示 秒: 1秒

clock_t 起始值: 1001
clock_t 终止值: 2001
clock_t显示毫秒: 1000毫秒

GetTickCount() 起始值: 82684882
GetTickCount() 终止值: 82685880
GetTickCount() 显示毫秒: 998毫秒

本机高精度计时器频率:2.4741e+006
第一次计时器值: 205054600159
第二次计时器值: 205057074204
计时器差: 2474045
QueryPerformanceCounter()显示微秒: 999.977微秒


你可能感兴趣的:(c,测试,null,Integer)