gettimeofday() -- 获取当前时间

本文介绍了gettimeofday()函数的使用方法,该函数用于获取当前时间,并保存在timeval结构体中。文章通过示例代码展示了如何调用此函数,并解释了timeval结构体中的字段含义及其单位换算。

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

gettimeofday() -- 获取当前时间(保存在结构体timeval中)
#include <stdio.h>
#include <sys/time.h>
#include <time.h>

int main(int argc, char * argv[]){

struct timeval tv; //(1)
while(1){
gettimeofday(&tv, NULL); //(2)
printf("time %u:%u\n", tv.tv_sec, tv.tv_usec);
sleep(2);
}
return 0;

}

(1) struct--timeval
--------------------------------------------------
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
millisecond 毫秒
microsecond 微秒

timeval表示一个时间点,比如:
timeval.tv_sec = 1 (s)
timevat.tv_usec = 500 000 (μs)
1:500 = 1s500000μs = 1.5s

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

The functions gettimeofday() and settimeofday() can get and set the time as well as a timezone.
The use of the timezone structure is obsolete; the tz argument should normally be specified as NULL.

(3) 运行结果:
--------------------------------------------------
time 1181788367:991487
time 1181788369:991602

表示睡眠2秒经过的精确时间为: 2s115μs

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值