linux时间-获取系统时间

基本概念

  1. 获取系统时间主要用到如下的结构与函数:
struct timeval
{
    long int tv_sec;      // 秒数
    long int tv_usec;     // 微秒数
}

相应的获取当前系统时间的函数:

#include 
int gettimeofday(struct timeval *tv, struct timezone *tz);

具有以下特点:
1.精确级别,微妙级别
2.受系统时间修改影响
3.返回的秒数是从1970年1月1日0时0分0秒开始

其参数 tv 是保存获取时间结果的结构体,参数 tz 用于保存时区结果。后者一半传入0即可。

代码

#include 
#include 

float time_diff( struct timeval* pbegin, struct timeval* pend ){

    int n = ( pend->tv_sec - pbegin->tv_sec ) * 1000000 + ( pend->tv_usec - pbegin->tv_usec );

    return 1.0 * n / 1000;

}

int main( void ){

    struct timeval begin;
    struct timeval end;

    gettimeofday( &begin, NULL );

    sleep(1);

    gettimeofday( &end, NULL );

    float diff = time_diff( &begin, &end );

    printf( "time diff is %fms.\n", diff );

    return 0;
}

你可能感兴趣的:(Linux系统编程)