学习日志(九)
Linux算时差的方法
时间函数
函数原型及头文件
#include<sys/time.h>
int gettimeofday(struct timeval *tv,struct timezone *tz );
结构体原型:
struct timeval
{
long tv_sec;/*秒*/
long tv_usec;/*微妙*/
};
struct timeval *tv :这个指针指向的结构体:里面放的当前时间和格林威治的时间的差(说白了就是放时间的)
struct timezone *tz :这个指针指向的结构体:里面放的是时区信息
gettimeofday() :会把当前时间和格林威治的时间的差值存放在tv结构体中。
当地时区的信息则放到tz所指的结构中。
测试功能:计算orangpepi zero2 在linux系统数数10000次耗时多少?
测试代码:
1 #include "sys/time.h"
2 #include "stdio.h"
3
4 void countTime()
5 {
6 int i,j;
7 for(i=0;i<100;i++){
8 for(j=0;j<100;j++);
9 }
10 }
11
12 int main()
13 {
14 struct timeval timestart;
15 struct timeval timestop;
16
17 gettimeofday(×tart,NULL);
18 countTime();
19 gettimeofday(×top,NULL);
20
21 long difftime = 1000000*(timestop.tv_sec-timestart.tv_sec)+(timestop.tv_usec-timestart.tv_usec);
22 printf("H616 count 1w = %ld usec \n",difftime);
23 return 0;
24 }
25
结果: