Linux C 获取时间戳

9 篇文章 0 订阅

1. 头文件

 #include <sys/time.h>

2. 代码

#include <iostream>
#include <sys/time.h>


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 <sys/time.h>
       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 */
    };
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值