linux获取系统时间戳

linux获取系统时间戳

#include<iostream>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>

int main(){
    
    
    struct timeval tv;
    gettimeofday(&tv,NULL);
    printf("second:%ld\n",tv.tv_sec);  //秒
    printf("millisecond:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000);  //毫秒
    printf("microsecond:%ld\n",tv.tv_sec*1000000 + tv.tv_usec);  //微秒

    sleep(3); // 为方便观看,让程序睡三秒后对比
    std::cout << "3s later:" << std::endl;

    gettimeofday(&tv,NULL);
    printf("second:%ld\n",tv.tv_sec);  //秒
    printf("millisecond:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000);  //毫秒
    printf("microsecond:%ld\n",tv.tv_sec*1000000 + tv.tv_usec);  //微秒
    return 0;
}

上面的结构体系统已经定义好了,不用自己定义,只需要将#include <sys/time.h>包含即可,在相关结构体中如下:

struct timeval{
    
     
 long tv_sec; //秒 
long tv_usec; //微秒 
}; 

猜你喜欢

转载自blog.csdn.net/mao_hui_fei/article/details/110383258