Linux常用时间函数


time()函数:

NAME
time - get time in seconds

 

SYNOPSIS
#include <time.h>

time_t time(time_t *tloc);

/* typedef long     time_t; */

 

DESCRIPTION
time() returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).

If tloc is non-NULL, the return value is also stored in the memory pointed to by tloc.

返回从公元1970-01-01的UTC时间 从00:00:00 到现在所经历的描述,如果tloc非空,返回值也会存储到tloc指向的内存

 

RETURN VALUE
On success, the value of time in seconds since the Epoch is returned. On error, ((time_t) -1) is returned, and errno is set appropriately.

执行成功,返回秒数

执行失败,返回-1

 

localtime()函数

作用:

localtime是 把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间

原型:

struct tm *localtime(const time_t *timer)

  • const time_t *time:这是指向表示日历时间的 time_t 值的指针,由time()函数返回

返回值:

struct tm定义如下:

struct tm {
   int tm_sec;         /* 秒,范围从 0 到 59 */
   int tm_min;         /* 分,范围从 0 到 59 */
   int tm_hour;        /* 小时,范围从 0 到 23 */
   int tm_mday;        /* 一月中的第几天,范围从 1 到 31 */
   int tm_mon;         /* 月份,范围从 0 到 11  */
   int tm_year;        /* 自 1900 起的年数 */
   int tm_wday;        /* 一周中的第几天,范围从 0 到 6 */
   int tm_yday;        /* 一年中的第几天,范围从 0 到 365 */
   int tm_isdst;       /* 夏令时 */ };

 

例子:

#include <stdio.h>
#include <time.h>
 
int main ()
{
   time_t rawtime;
   struct tm *info;
   char buffer[80];
 
   time( &rawtime );
 
   info = localtime( &rawtime );
   printf("当前的本地时间和日期:%s", asctime(info));
 
   return(0);
}

 

 

asctime()函数

原型:

char* asctime (const struct tm * timeptr)

作用:

 把timeptr指向的tm结构体中储存的时间转换为字符串,返回的字符串格式为:Www Mmm dd hh:mm:ss yyyy。其中Www为星期;Mmm为月份;dd为日;hh为时;mm为分;ss为秒;yyyy为年份。

参数:

  • const struct tm * timept:由localtime()函数返回

返回值:

时间字符串

例子: 

/* asctime example */
#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, struct tm, time, localtime, asctime */
 
int main ()
{
    time_t rawtime;
    struct tm * timeinfo;
 
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );
    printf ( "The current date/time is: %s", asctime (timeinfo) );
 
    return 0;
}
函数范例的输出:
The current date/time is: Wed Feb 13 15:46:46 2018

 

gettimeofday()函数

原型:

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

作用:

获得当前精确时间(1970年1月1日到现在的时间),或者为执行,可以使用gettimeofday()函数。

参数:

  • struct timeval*tv

    struct timeval{
    long int tv_sec; // 秒数
    long int tv_usec; // 微秒数
    }


  • struct timezone *tz

    struct timezone{
    int tz_minuteswest;  /*格林威治时间往西方的时差*/
    int tz_dsttime;/*DST 时间的修正方式*/
    }

返回值:

执行成功,返回0

执行失败,返回-1

例子:

它获得的时间精确到微秒(1e-6 s)量级。在一段代码前后分别使用gettimeofday可以计算代码执行时间:

struct timeval tv_begin, tv_end;
gettimeofday(&tv_begin, NULL);
foo();
gettimeofday(&tv_end, NULL);

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM