c++ 程序运行时间总结测试代码:
#include <iostream>
#include <Windows.h>
#include<time.h>
#include <iomanip>
using namespace std;
void timeConsuming()
{
int i = 100;
while (i > 0)
{
Sleep(10);
i--;
}
}
// 利用clock()函数实现程序时间的统计,其中start_time 表示此进程从开始运行到开始
//统计时间所用过的时间,然后利用CLOCKS_PER_SEC获取实际时间,统计精度为 毫秒;
void clock_t_type()
{
clock_t start_time , end_time;
start_time = clock();
timeConsuming();
end_time = clock();
//此处注意 clock_t 为long 类型,在进行相除的时候若想获得精确时间,需要分子强制类型转换为double类型。
double duration = (double)(end_time - start_time)/CLOCKS_PER_SEC;
cout << left << setw(25) <<setfill(' ') << "clock type : " ;
cout << duration << " seconds" << endl;
}
// GetTickCount返回从系统启动到当前的时间,单位为毫秒 , 可以和Sleep 函数结合使用
// 若系统运行时间超过49.71天时,这个数就会归0,
void GetTickCount_Type()
{
DWORD start_time , end_time , duration;
start_time = GetTickCount();
timeConsuming();
end_time = GetTickCount();
duration = end_time - start_time;
cout << left << setw(25 ) << setfill(' ') << "GetTickCount type : ";
cout << duration/1000.0 << " seconds" << endl;
}
// QueryPerformanceFrequency 高精度计时器 ;类型:Win32API
// 要求计算机从硬件上支持高精度定时器。
// 返回值的单位为 秒
void QueryPerformanceFrequency_type()
{
LARGE_INTEGER time_start;
LARGE_INTEGER time_end;
LARGE_INTEGER current_f;
double frequency;
QueryPerformanceFrequency(¤t_f); // 作用:返回硬件支持的高精度计数器的频率。
frequency = current_f.QuadPart;
QueryPerformanceCounter(&time_start);
timeConsuming();
QueryPerformanceCounter(&time_end);
double duration = (time_end.QuadPart - time_start.QuadPart)/frequency;
//cout << "frequency : " << frequency << endl;
//cout << "time start : " << time_start << endl;
//cout << "time_end : " << time_end << endl;
cout << left << setw(25 ) << setfill(' ');
cout << "QueryPerformance time: " << duration <<":seconds" << endl;
}
//The time function returns the number of seconds elapsed since midnight (00:00:00), January 1, 1970,
//Coordinated Universal Time (UTC), 单位:秒
void time_type()
{
time_t time_start , time_end;
time_start = time(NULL);
timeConsuming();
time_end = time(NULL);
cout << left << setw(25 ) << setfill(' ');
cout << "time_type time: " << (time_end - time_start) <<":seconds" << endl;
}
// 利用 GetLocalTime 获取当前的年月日
void get_current_time()
{
SYSTEMTIME sys;
GetLocalTime(&sys);
cout<<sys.wYear<<"年";
cout<<sys.wMonth<<"月";
cout<<sys.wDay<<"日";
cout<<sys.wHour<<"时";
cout<<sys.wMinute<<"分";
cout<<sys.wSecond<<"秒";
cout<<sys.wMilliseconds<<"毫秒";
cout<<",星期"<<sys.wDayOfWeek<<endl;
}
int main()
{
get_current_time();
clock_t_type();
GetTickCount_Type();
QueryPerformanceFrequency_type();
time_type();
return 0;
}