时间函数(gettimeofday)使用

本文详细介绍了 gettimeofday 函数的功能及用法,该函数能够获取当前精确时间(1970年1月1日至今的时间),适用于需要高精度时间记录的应用场景。文中还提供了示例代码,展示了如何在 C 语言程序中调用此函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 函数功能:

gettimeofday是计算机函数,使用C语言编写程序需要获得当前精确时间(1970年1月1日到现在的时间),或者为执行计时,可以使用gettimeofday()函数。

2. 函数原型:

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

3. 头文件:

#include <sys/time.h>

4.说明:

其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果:
timezone 参数若不使用则传入NULL。

struct timeval {
               time_t      tv_sec;     // seconds 秒
               suseconds_t tv_usec;    // microseconds 微秒
           };
struct timezone {
               int tz_minuteswest;     /* minutes west of Greenwich 格林威治时间往西方的时差 */ 
               int tz_dsttime;         /* type of DST correction 时间的修正方式*/
           };
返回值:
gettimeofday() and settimeofday() return 0 for success, or -1 for failure
示例:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
/*
int gettimeofday(struct timeval *tv, struct timezone *tz);
struct timeval {
               time_t      tv_sec;     // seconds 
               suseconds_t tv_usec;    // microseconds
           };

*/

int get_time(struct timeval *tm)
{
    int res;
    res = gettimeofday(tm, NULL);
    return res;
}

int main(int argc, char *argv[])
{
    int ret=0;
    struct timeval now;

    while(1)
    {
        ret = get_time(&now);
        if(ret) return -1;
        printf("now_seconds=%ld,now_microseconds=%ld \n", now.tv_sec, now.tv_usec);
        sleep(1);   
    }
    return 0;   
}

执行结果:

dawsen@KeVen:/mnt/m/work/time$ ./time
now_seconds=1526134532,now_microseconds=652143
now_seconds=1526134533,now_microseconds=653081
now_seconds=1526134534,now_microseconds=653895
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值