# 【原创】C语言时间函数简介

======

C 库与 C++ 库的关系
The C++ library includes the same definitions as the C language library organized in the same structure of header files, with the following differences:
a. Each header file has the same name as the C language version but with a "c" prefix and no extension. For example, the C++ equivalent for the C language header file <stdlib.h> is <cstdlib>.
b. Every element of the library is defined within the std namespace.

C 标准与 C++ 标准之间的关系
C++98 includes the C library as described by the 1990 ISO C standard and its amendment #1 (ISO/IEC 9899:1990 and ISO/IEC 9899:1990/DAM 1).

C++11 includes the C library as described by the 1999 ISO C standard and its Technical Corrigenda 1, 2 and 3 (ISO/IEC 9899:1999 and ISO/IEC 9899:1999/Cor.1,2,3), plus <cuchar> (as by ISO/IEC 19769:2004).

Other introductions by the 2011 ISO C standard are not compatible with C++.

======

time_t】 -- Time type
Alias of a fundamental arithmetic type capable of representing times, as those returned by function time.

For historical reasons, it is generally implemented as an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC (i.e., a unix timestamp). Although libraries may implement this type using alternative time representations.

Portable programs should not use values of this type directly, but always rely on calls to elements of the standard library to translate them to portable types(such as localtime, gmtime or difftime).

struct tm】 -- Time structure
Structure containing a calendar date and time broken down into its components.

The structure contains nine members of type int (in any order), which are:
 Member Type Meaning Range tm_sec int seconds after the minute 0-61* tm_min int minutes after the hour 0-59 tm_hour int hours since midnight 0-23 tm_mday int day of the month 1-31 tm_mon int months since January 0-11 tm_year int years since 1900（ 这个值需要注意下 ） tm_wday int days since Sunday 0-6 tm_yday int days since January 1 0-365 tm_isdst int Daylight Saving Time flag

time()

time_t time (time_t* timer);

Get current time （获取当前时间

Get the current calendar time as a value of type time_t.

Data races
The object pointed by timer is modified (if not null).

localtime()

struct tm * localtime (const time_t * timer);

Convert time_t to tm as local time（转换为本地时区时间

Uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed for the local timezone.

The returned value points to an internal object whose validity or value may be altered by any subsequent call to gmtime or localtime.

Data races
The function accesses the object pointed by timer.
The function also accesses and modifies a shared internal object, which may introduce data races on concurrent calls to gmtime and localtime. Some libraries provide an alternative function that avoids this data race: localtime_r (non-portable).

gmtime()

struct tm * gmtime (const time_t * timer);

Convert time_t to tm as UTC time（转换为 GMT 时区时间

Uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed as a UTC time (i.e., the time at the GMT timezone).

The returned value points to an internal object whose validity or value may be altered by any subsequent call to gmtime or localtime.

Data races
The function accesses the object pointed by timer.
The function also accesses and modifies a shared internal object, which may introduce data races on concurrent calls to gmtime and localtime. Some libraries provide an alternative function that avoids this data race: gmtime_r (non-portable).

ctime()

char* ctime (const time_t * timer);

Convert time_t value to string 将 time_t 对应的数字时间值转换成时间字符串

Interprets the value pointed by timer as a calendar time and converts it to a C-string containing a human-readable version of the corresponding time and date, in terms of local time.

The returned string has the following format:
Www Mmm dd hh:mm:ss yyyy

Where Www is the weekday, Mmm the month (in letters), dd the day of the month, hh:mm:ss the time, and yyyy the year.

The string is followed by a new-line character ('\n') and terminated with a null-character.

This function is equivalent to:

asctime ( localtime (timer))

For an alternative with custom date formatting, see strftime.

The returned value points to an internal array whose validity or value may be altered by any subsequent call to asctime or ctime.

Data races
The function accesses the object pointed by timer.
The function also accesses and modifies a shared internal buffer, which may cause data races on concurrent calls to asctime or ctime. Some libraries provide an alternative function that avoids this data race: ctime_r (non-portable).

asctime()

char* asctime (const struct tm * timeptr);

Convert tm structure to string 转换 tm 结构中的内容成时间字符串

Interprets the contents of the tm structure pointed by timeptr as a calendar time and converts it to a C-string containing a human-readable version of the corresponding date and time.

The returned string has the following format:
Www Mmm dd hh:mm:ss yyyy

Where Www is the weekday, Mmm the month (in letters), dd the day of the month, hh:mm:ss the time, and yyyy the year.

The string is followed by a new-line character ('\n') and terminated with a null-character.

For an alternative with custom date formatting, see strftime.

The returned value points to an internal array whose validity or value may be altered by any subsequent call to asctime or ctime.

Data races
The function accesses the object pointed by timeptr.
The function also accesses and modifies a shared internal buffer, which may cause data races on concurrent calls to asctime or ctime. Some libraries provide an alternative function that avoids this data race: asctime_r (non-portable).

strftime()

size_t strftime (char* ptr, size_t maxsize, const char* format, const struct tm* timeptr );

Format time as string 将 tm 结构中保存的时间值格式化成指定形式的字符串

Copies into ptr the content of format, expanding its format specifiers into the corresponding values that represent the time described in timeptr, with a limit of maxsize characters.

ptr -- Pointer to the destination array where the resulting C string is copied.
maxsize -- Maximum number of characters to be copied to ptr, including the terminating null-character.
format -- C string containing any combination of regular characters and special format specifiers. These format specifiers are replaced by the function to the corresponding values to represent the time specified in timeptr. They all begin with a percentage (%) sign, and are:
...
timeptr -- Pointer to a tm structure that contains a calendar time broken down into its components (see struct tm).

Return Value 返回值
If the length of the resulting C string, including the terminating null-character, doesn't exceed maxsize, the function returns the total number of characters copied to ptr (not including the terminating null-character).
Otherwise, it returns zero, and the contents of the array pointed by ptr are indeterminate.

Compatibility 兼容性问题
Particular library implementations may support additional specifiers or combinations.
Those listed here are supported by the latest C and C++ standards (both published in 2011), but those in yellow were introduced in C99 (only required for C++ implementations since C++11), and may not be supported by libraries that comply with older standards.

Data races
The function accesses the array pointed by format and the object pointed by timeptr. On success, it also modifies the elements in the array pointed by ptr.
Concurrently changing locale settings may also introduce data races.

======

1. 使用 gettimeofday() 提供精度到毫秒的时间戳（可以到微秒级别）
 1 2 3 4 5 6 7 8 {     struct timeval tv;       gettimeofday(&tv,NULL);     off = strftime(buf,sizeof(buf),"%d %b %H:%M:%S.",localtime(&tv.tv_sec));     snprintf(buf+off,sizeof(buf)-off,"%03d",(int)tv.tv_usec/1000);     fprintf(fp,"[%d] %s %c %s\n",(int)getpid(),buf,c[level],msg); }

2. 使用 time()提供精度到秒的时间戳

 1 2 3 4 5 6 7 {     time_t t;     t = time( NULL );     local = localtime( &t );     timestr = asctime( local );     fprintf( stderr, "%s\n", timestr ); }

• times() 用来统计进程及其子进程执行所消耗的 CPU 时间。常见用法是在不同地方调用两次这个函数，从而可以计算出进程或子进程在这两次调用之间消耗了多少 CPU 时间。
• time() 返回当前相对于 Epoch (在 linux/unix 里，这个时间一般指 1970 年 1 月 1 日 0 点 0 分 0 秒）所经过的秒数。 常见用法是在不同地方调用两次这个函数，从而可以计算这两处调用之间系统时间过了多少秒。
• gettimeofday() 有点类似于 time()，获取当前相对于 Epoch 所经过的秒数+微秒数
• clock() 返回当前进程消耗的 CPU 时间，用法类似于 times()，函数返回值是否包含等待子进程的时间，在不同的实现中是不一样的，在 linux 里不包含。
由上可见， times() 和 clock() 可以算成一类，用来计算 CPU 时间； time() 和 gettimeofday() 可以算成一类，都是用来计算真实时间的。

time 和 gettimeofday 的性能差异

两个都是 glibc 中实现的获取时间的函数，gettimeofday() 支持获取微秒级别的时间精度，time() 支持获取秒级时间精度，两者在性能上有差别吗?
其实，基本上没有多少性能差别，因为 time() 其实就是把 gettimeofday() 包装了一层。但是测试过程中发现 time() 比 gettimeofday() 性能好了一点点， 可能是 time() 函数的接口形式简单吧，堆栈处理快的缘故。

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #include        /* For NULL.  */ #include  #include      /* Return the current time as a time_t' and also put it in *T if T is    not NULL.  Time is represented as seconds from Jan 1 00:00:00 1970.  */ time_t time (t)      time_t *t; {   struct timeval tv;   time_t result;     if (__gettimeofday (&tv, (struct timezone *) NULL))     result = (time_t) -1;   else     result = (time_t) tv.tv_sec;     if (t != NULL)     *t = result;   return result; }`
由上面可知，如果你的时间戳不要求达到毫秒级别，那么其实不需要使用 gettimeofday()；否则一旦使用，就需要处理 windows() 平台上的移植问题。

+ 订阅