目录
统计时间
Windows &&linux通用
high_resolution_clock
C++使用chrono获取时间差
#include <iostream>
#include <chrono>
int main(){
auto start = std::chrono::high_resolution_clock::now();
int res = 1;
for(int i=0; i<100000; i++){
res++;
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> tm = end - start; // 毫秒
// std::chrono::duration<double, std::micro> tm = end - start; 微秒
std::cout << "time: " << tm.count() << "ms" << std::endl;
return 0;
}
Windows环境
1. 获取当前时间,可精确到秒(Windows)
获取时间
1 使用 time_t time( time_t * timer ) 精确到秒
3 计算时间差使用 double difftime( time_t timer1, time_t timer0 )
#include <iostream>
#include <ctime>
int main(){
time_t tv;
tv = time(NULL);//time(&tv); get current time;
std::cout << tv << std::endl;//距离1970-01-01 00:00:00经历的秒数
std::cout << ctime(&tv) << std::endl;//显示当前时间
tm *local;
local = localtime(&tv);
std::cout << asctime(local) << std::endl;//显示当前时
return 0;
}
2.精确到毫秒
4 使用 DWORD GetTickCount() 精确到毫秒
(1).<windows.h>
<windows.h>
#include <iostream>
#include <windows.h>
int main(){
DWORD t_start, t_end;
t_start = GetTickCount();//从操作系统启动所经过(elapsed)的毫秒数,它的返回值是DWORD。
Sleep(3000);
t_end = GetTickCount();
std::cout << t_end - t_start << std::endl;
return 0;
}
(2). <timeb.h>
#include <iostream>
#include <sys\timeb.h>
long long getSystemTime(){
timeb t;
ftime(&t);
return t.time * 1000 + t.millitm;
}
int main(){
long long t_start = getSystemTime();
Sleep(3000);
long long t_end = getSystemTime();
std::cout << t_end - t_start << std::endl;
return 0;
}
---------------------
原文:https://blog.csdn.net/kangruihuan/article/details/59055801
clock() 函数 , 用 clock() 函数,得到系统启动以后的毫秒级时间,然后除以 CLOCKS_PER_SEC ,就可以换成“秒”,标准 c 函数。
使用该函数可以得到启动到函数调用占用CPU的时间。这个函数返回从“启动程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,其中clock_t是用来保存时间的数据类型。
#define CLOCKS_PER_SEC <integer constant expression > 0>
clock_t clock ( void );
#include clock_t t = clock();
long sec = t / CLOCKS_PER_SEC; (CLOCKS_PER_SEC 这个在头文件中找到定义)
他是记录时钟周期的,实现看来不会很精确,需要试验验证;
#include <time.h>
void main()
{
clock_t start_time, end_time;
start_time = clock(); //获取开始执行时间
xxxxxxx; //过程
end_time = clock(); //获取结束时间
double Times = (double)(end_time - start_time) / CLOCKS_PER_SEC;
printf("%f seconds\n", Times);
}
gettime(&t); 据说 tc2.0 的 time 结构含有毫秒信息
#include
#include
int main(void)
{
struct time t;
gettime(&t);
printf("The current time is: -:d:d.d/n",
t.ti_hour, t.ti_min, t.ti_sec, t.ti_hund);
return 0;
}
time 是一个结构体,, 其中成员函数 ti_hund 是毫秒。。。
GetTickCount(), 这个是 windows 里面常用来计算程序运行时间的函数;
DWORD dwStart = GetTickCount();
// 这里运行你的程序代码
DWORD dwEnd = GetTickCount();
则 (dwEnd-dwStart) 就是你的程序运行时间 , 以毫秒为单位
这个函数只精确到 55ms , 1 个 tick 就是 55ms 。
#include <iostream>
#include <windows.h>
void main()
{
long start_time = GetTickCount(); //获取开始执行时间
xxxxxxx; //过程
long end_time = GetTickCount(); //获取结束时间
long Times = end_time-start_time;
printf("%f seconds\n", Times);
}
timeGetTime()t,imeGetTime() 基本等于 GetTickCount() ,但是