程序的运行效率很重要,为了明确到底是那一块代码浪费时间,浪费多少时间,检测一下是很有必要的,用下面的方法可以精确地统计时间。第一种精确到秒,第二种精确到毫秒,第三种精确到0.000001秒,大家可以根据自己的需求选用
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
int main()
{
//精确到秒 ==========================================
time_t t1,t2;
time(&t1);
//此处放置要测试的代码
Sleep(1000);//延时
time(&t2);
printf("%d %d %d秒\n",t1,t2,t2-t1);
//精确到毫秒 ========================================
clock_t c1,c2;
c1=clock();
//此处放置要测试的代码
Sleep(100);//延时
c2=clock();
printf("%d %d %d毫秒\n",c1,c2,c2-c1);
//精确到 0.000001毫秒 ===============================
LARGE_INTEGER litmp;
LONGLONG start, end;
double dft, dff, dfm;
QueryPerformanceFrequency(&litmp);//获得时钟频率
dff = (double) litmp.QuadPart;
QueryPerformanceCounter(&litmp);//获得初始值
start = litmp.QuadPart;
//此处放置要测试的代码
Sleep(1000);//延时
QueryPerformanceCounter(&litmp);//获得终止值
end = litmp.QuadPart;
dfm = (double) (end - start);
dft = dfm / dff;//获得对应的时间值,单位秒
printf("%lf毫秒\n",dfm/dff*1000);
}
精确记算程序的运行时间或者某段代码的运行时间
最新推荐文章于 2025-02-12 11:09:09 发布