Linux C 获取时间戳

1. 头文件

 #include 

2. 代码

#include 
#include 


using namespace std;


// 获取当前时间戳
// 单位: 秒
double now() {
	// 创建结构体
    struct timeval tv = { 0, 0 };
    // 调用函数,将当前的时间戳写入 结构体 tv 中
    gettimeofday(&tv, NULL);
    // 获取结构体的 “s” 和 “μs” 信息
    return tv.tv_sec + tv.tv_usec / 1000000.0;
}

int main() {

    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;

    return 0;
}

3. 结构体源码

SYNOPSIS
       #include 
       int gettimeofday(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
// 结构体
struct timeval {
        time_t      tv_sec;     /* seconds */
        suseconds_t tv_usec;    /* microseconds */
    };

你可能感兴趣的:(C++,linux,linux)