C标准库time.h使用说明

// 作者:Michael
// 时间:2014 - 5 -12
近期学习C++标准库时,我发现time.h(ctime)里一些函数经常导致自己困惑或者是误用,因此打算自己写一篇文章总结下time.h(ctime)里函数,也算是回答自己的一些困惑,同时也希望对读者有一点作用。

time.h是C标准函数库中获取时间与日期、对时间与日期数据操作及格式化的头文件。tim.h wiki链接
【注】不知为何WIKI里有些函数我并没有找到。

一、头文件

头文件包括函数定义、宏定义以及类型定义。
1.函数

// Time manipulation(时间操作)
clock_t clock(void)
double difftime(time_t end, time_t beginig)
time_t mktime(struct tm* ptm)
time_t time(time_t* timer)

// Conversion(转换)
char *asctime(const struct tm* tmptr)
char* ctime(const time_t* timer)
struct tm* gmtime(const time_t* timer)
struct tm* localtime(const time_t* timer)
size_t strftime(char* s, size_t n, const char* format, const struct tm* tptr)

2. 宏定义
CLOCKS_PER_SEC
NULL
3. 类型
clock_t:时钟类型
size_t:无符号整形
time_t:时间类型
struct tm:时间结构体

二、用法

  1. 最常用的当然是计算一段代码执行时间了,那么需要可以用两个函数:
    clock以及time两个函数。

使用clock函数代码段如下:

// using clock function

// code befor calculate time
clock_t start, end;
start = clock();
// code here, for example
for( int i = 0; i < 100; i++)
    ;
end = clock();
printf("%f", (double)(end - start) / CLOCKS_PER_SEC;

使用time函数代码段:

// using time function

// code befor calculate time
double sec
time_t time; 
// code to do, for example
time = time(NULL);
for( int i = 0; i < 100; i++)
    ;
seconds = difftime( time, time());
printf("Elapsed %f seconds
", seconds);

总结:两个函数从精度来比较的话,推荐使用clock函数,因为其能达到ms级精度,而time的话只能达到s级。

  1. mktime函数功能功能纯粹是将时间结构体变量*ptm转换为time_t变量, 至此时间操作函数则讲完。

  2. 上面已经介绍了头文件中变量包括 time_t``struct tm,那么出现一个问题:

如何将这些变量转换成字符串呢?也就是指定一个变量,如何输出或者存储到文件?

库函数里面提供了丰富的转换函数,包括ctime``asctime以及strftime。个人认为strftime使用概率远远小于前两个。因此可以需要时查阅资料而不用过度关注此函数。

Exapmle(例子):

/* 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;
}

而ctime据说很有可能是通过localtime以及上面的asctime函数转换实现的,即asctime(localtime(timer)

Tips: ctime显示的是local time, 即本地时间。而不是GM时间。

Example(例子):

/* ctime example */
#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, time, ctime */

int main ()
{
  time_t rawtime;

  time (&rawtime);
  printf ("The current local time is: %s", ctime (&rawtime));

  return 0;
}

4. localtime以及gmtime
这两个函数主要是将time_t变量转换为struct tm结构体。一个是本地时间,一个GM时间-GMT时区时间,因此比较简单

三、总结

这篇文章主要介绍了C标准库里time.h的函数、宏以及变量,区分性地介绍了函数的使用。

原文地址:https://www.cnblogs.com/miraclecoder/p/4051183.html