c++时间函数总结
早就准备要写技术总结,没想到第一篇写了C++。这几天看了下时间函数,决定总结一下。
根据了解查阅,c++在程序中获得时间的常用方式有三种,总结如下。
一.gettimeofday()
本段参考链接:https://blog.csdn.net/m0_37263637/article/details/79089242
函数定义:int gettimeofday(struct timeval *tv, struct timezone *tz);
头文件 : #include <sys/time.h> (一定要加sys)
结构体:timeStart.tv_sec 这个就是秒为单位的时间戳。
timeStart.tv_usec 这是当前秒中的微秒数(原文写的是毫秒,是错误的)。
用法示例:
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
int main(void){
struct timeval timeStart, timeEnd, timeSystemStart; //定义结构体
double runTime=0, systemRunTime;
gettimeofday(&timeSystemStart, NULL );
while(1){
gettimeofday(&timeStart, NULL ); //获取当前时间
usleep(300000);
gettimeofday( &timeEnd, NULL );
runTime = (timeEnd.tv_sec - timeStart.tv_sec ) + (double)(timeEnd.tv_usec -timeStart.tv_usec)/1000000; //计算时间差
systemRunTime = (timeEnd.tv_sec - timeSystemStart.tv_sec ) + (double)(timeEnd.tv_usec -timeSystemStart.tv_usec)/1000000;
printf("runTime is %lf\n", runTime);
printf("systemRunTime is %lf\n", systemRunTime);
}
return 0;
}
该函数返回的是地理时间,跟时区相关,可以看成是绝对时间,加几行代码就可以换算成日常使用的时间,两个时间相减则是运行时间。此函数最好用,以后都使用该函数
二:clock()
参考链接1:https://blog.csdn.net/m0_37251750/article/details/102581935
参考链接2:https://blog.csdn.net/weixin_43725617/article/details/104194499
头文件: #include<time.h>或者#include
结构体:clock_t,实际为long 类型
还有一个相关的宏:#define CLOCKS_PER_SEC ((clock_t)1000),表示每秒钟的计数单元
用法示例:
#include<iostream>
#include<time.h>
using namespace std;
int main()
{
int m = 0;
clock_t start, end;
start = clock();
for (int i = 0; i < 1e3; i++)
{
for (int j = 0; j < 1e3; j++)
{
m++;
}
}
end = clock();
double duration=(double)(end-start)/ CLOCKS_PER_SEC;
cout << m<<" ticks need " << duration << "seconds" << endl;
return 0;
}
注:这个函数返回的是从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,因此是一个相对时间,配合宏才能算出时间差,同时要注意,使用cin用户输入时,时间是不计算的(有文章说包含,但是实测输入等待时间是不计算在内的)。
如果CPU计数单元为1000000,则两个函数精度相同。
三GetTickCount()函数
参考链接:https://blog.csdn.net/m0_37251750/article/details/102581935
函数定义:DWORD GetTickCount(void);
头文件:winbase.h,windows程序设计中可以使用头文件windows.h
示例代码
#include<iostream>
2 #include<Windows.h>
3 using namespace std;
4 int main()
5 {
6 DWORD startTime = GetTickCount();//计时开始
7 for (int i = 0; i < 2147483640; i++)
8 {
9 i++;
10 }
11 DWORD endTime = GetTickCount();//计时结束
12 cout << "The run time is:" << endTime - startTime << "ms" << endl;
13 system("pause");
14 return 0;
15 }
GetTickcount函数:它返回从操作系统启动到当前所经过的毫秒数,常常用来判断某个方执行的时间,其函数原型是DWORD GetTickCount(void),返回值以32位的双字类型DWORD存储,因此可以存储的最大值是(2^32-1) ms约为49.71天,因此若系统运行时间超过49.71天时,这个数就会归0,MSDN中也明确的提到了:“Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days.”。因此,如果是编写服务器端程序,此处一定要万分注意,避免引起意外的状况。
特别注意:这个函数并非实时发送,而是由系统每18ms发送一次,因此其最小精度18ms。当需要有小于18ms的精度计算时,应使用StopWatch方法进行。用clock()函数计算运行时间,表示范围一定大于GetTickCount()函数,所以,建议使用clock()函数。
此函数与系统相关,windows开发使用,本人使用linux,所以没有具体使用过。
关于时间函数的总结就这么多,第一次写格式还不熟悉,行文比较乱,以后改进。