2025年3月15日 星期六 甲辰(龙)年 月十四 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

c语言获取时间

时间:03-30来源:作者:点击数:64

gettimeofday()函数的使用方法

1.简介:

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

2.函数原型:

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

3.说明:

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

4.结构体:

1. timeval 结构体定义:

  • struct timeval{
  • long tv_sec; /*秒*/
  • long tv_usec; /*微妙*/
  • };

2. timezone 结构定义:

  • 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>
  • void hello_world(void)
  • {
  • printf("Hello world!!!!\r\n");
  • }
  • int main(void)
  • {
  • struct timeval tv_begin,tv_end;
  • gettimeofday(&tv_begin,NULL);
  • hello_world();
  • gettimeofday(&tv_end,NULL);
  • printf(“tv_begin_sec:%d\n”,tv_begin.tv_sec);
  • printf(“tv_begin_usec:%d\n”,tv_begin.tv_usec);
  • printf(“tv_end_sec:%d\n”,tv_end.tv_sec);
  • printf(“tv_end_usec:%d\n”,tv_end.tv_usec);
  • return 0;
  • }

//统计耗时,单位ms

int times = (tv_end.tv_sec*1000+tv_end.tv_usec/1000) - (tv_begin.tv_sec*1000+tv_begin.tv_usec/1000);

说明:在使用gettimeofday()函数时,第二个参数一般都为空,因为我们一般都只是为了获得当前时间,而不用获得timezone的数值

time函数

函数声明:time_t time (time_t *__timer);

其中time_t为time.h定义的结构体,一般为长整型

time函数返回的为unix时间戳,即从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒。

如果参数__timer非空,会存储相同值到__timer指向的内存中。

localtime函数,返回年月日时分秒

函数声明:struct tm *localtime (const time_t *__timer);

tm为一个结构体,包含了年月日时分秒等信息

  • #include <stdio.h>
  • #include <time.h>
  • int main ()
  • {
  • time_t t;
  • struct tm * lt;
  • time (&t);//获取Unix时间戳。
  • lt = localtime (&t);//转为时间结构。
  • printf ( "%d/%d/%d %d:%d:%d\n",lt->tm_year+1900, lt->tm_mon+1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec);//输出结果
  • return 0;
  • }
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门