天天看点

C语言-程序耗时计算

算法耗时处理:

1.time_t:获取1970年1月1日到现在的0区秒数,精确秒

头文件:time.h

使用平台:跨平台

函数声明:time_t time(time_t *t);

代码示例:

time_t start,end;
time(&start);
...
time(&end);
           

2.clock_t:计时所表示的是占用CPU的时钟单元,精确到毫秒

头文件:time.h

使用平台:跨平台

函数声明:

clock_t clock(void) ;

clock()返回单位是毫秒。如果想返用秒为单位可以用

代码示例:

duration = (finish - start) / CLOCKS_PER_SEC;
double duration;
clock_t start, finish;

start = clock();
...
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
           

2.gettimeofday:是Linux下获得当前的秒和微秒的时间

头文件:sys/time.h

使用平台:linux

函数声明:

int gettimeofday(struct  timeval *tv, struct  timezone *tz )

当前的时间存放在tv 结构体中,当地时区的信息则放到tz所指的结构体中,tz可以为空。

函数执行成功后返回0,失败后返回-1。

结构体timeval:

struct timeval

{

  long  tv_sec;  // 1970年1月1日到现在的秒。

  long  tv_usec; // 当前秒的微妙,即百万分之一秒。

};

struct timezone

{

  int tz_minuteswest;  // 和UTC(格林威治时间)差了多少分钟。

  int tz_dsttime;      // type of DST correction,修正参数据,忽略

};

代码示例:

struct timeval tv;
struct timezone tz;    
struct tm *t;
    
gettimeofday(&tv, &tz);
//printf("tv_sec:%ld\n",tv.tv_sec);
//printf("tv_usec:%ld\n",tv.tv_usec);
//printf("tz_minuteswest:%d\n",tz.tz_minuteswest);
//printf("tz_dsttime:%d\n",tz.tz_dsttime);
t = localtime(&tv.tv_sec);
printf("time_now:%d-%d-%d %d:%d:%d.%ld\n", 1900+t->tm_year, 1+t->tm_mon, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, tv.tv_usec);
           

4.GetTickCount:计算从操作系统启动所经过(elapsed)的毫秒数,它的返回值是DWORD。

头文件:winbase.h

使用平台:跨平台(linux有相应的函数对应)

函数原型:

DWORD GetTickCount(void);

返回值以32位的双字类型DWORD存储,因此可以存储的最大值是(2^32-1) ms约为49.71天,因此若系统运行时间超过49.71天时,这个数就会归0

头文件:

C/C++头文件:winbase.h

windows程序设计中可以使用头文件windows.h

程序示例:

DWORD startTime = GetTickCount();//计时开始
...
DWORD endTime = GetTickCount();//计时结束
endTime - startTime ;
           

4.chrono

https://zhuanlan.zhihu.com/p/269982520

参考:

https://www.cnblogs.com/didiaodidiao/p/9194702.html

https://blog.csdn.net/xiaofei2010/article/details/8489014