Linux 时间函数之 gettimeofday() 函数之使用方法

来源:互联网 发布:淘宝优惠券群合法吗 编辑:程序博客网 时间:2024/05/21 10:48

原文链接:http://www.linuxidc.com/Linux/2012-06/61903.htm

一.gettimeofday() 函数的使用方法:

1.简介:

在 C 语言中可以使用函数 gettimeofday() 函数来得到时间。它的精度可以达到微妙

2.函数原型:

#include<sys/time.h>int gettimeofday(struct timeval* tv, struct timezone* tz)
3.说明:

gettimeofday() 会把目前的时间用 tv 结构体返回,当地时区的信息则放到 tz 所指的结构中

4.结构体:

struct timeval{    long tv_sec; // 秒    long  tv_usec; // 微妙};struct timezone{    int tz_minuteswest; // 和 greenwich 时间差了多少分钟    int tz_dsttime; // type of DST correction}
3>在 gettimeofday() 函数中 tv 或者 tz 都可以为空。如果为空则就不返回其对应的结构体。

4>函数执行成功后返回 0,失败后返回 -1,错误代码存于 errno 中。

5.程序实例:

#include <stdio.h>#include <sys/time.h>#include <unistd.h>int main() {    struct timeval tv;    struct timezone tz;    gettimeofday(&tv,&tz);    printf(“tv_sec: %d\n”, tv.tv_sec);    printf(“tv_usec: %d\n”, tv.tv_usec);    printf(“tz_minuteswest: %d\n”, tz.tz_minuteswest);    printf(“tz_dsttime: %d\n”, tz.tz_dsttime);}
说明:在使用 gettimeofday() 函数时,第二个参数一般都为空,

因为我们一般都只是为了获得当前时间,而不用获得 timezone 的数值

0 0
原创粉丝点击