#include<iostream>#include<sys/time.h>
using namespace std;// 获取当前时间戳// 单位: 秒doublenow(){// 创建结构体struct timeval tv ={0,0};// 调用函数,将当前的时间戳写入 结构体 tv 中gettimeofday(&tv,NULL);// 获取结构体的 “s” 和 “μs” 信息return tv.tv_sec + tv.tv_usec /1000000.0;}intmain(){double old_seconds =now();for(int i =0; i <1000000; i++){for(int j =0; j <200; j++);}double new_seconds =now();
cout << old_seconds << endl;
cout << new_seconds - old_seconds << endl;return0;}
3. 结构体源码
SYNOPSIS
#include<sys/time.h>intgettimeofday(struct timeval *tv,struct timezone *tz);
DESCRIPTION
The functions gettimeofday() and settimeofday() can get and set the time as well as a timezone. The tv argu-
ment is a struct timeval (as specified in <sys/time.h>):struct timeval {
time_t tv_sec;/* seconds */
suseconds_t tv_usec;/* microseconds */};
and gives the number of seconds and microseconds since the Epoch (see time(2)). The tz argument is a struct
timezone