difftime

< c‎ | chrono
定义于头文件 <time.h>
double difftime( time_t time_end, time_t time_beg );

以秒数计算二个作为 time_t 对象的日历时间的差( time_end - time_beg )。若 time_end 代表先于 time_beg 的时间点,则结果为负。

参数

time_beg, time_end - 待比较的时间

返回值

两时间之差的秒数。

注意

在 POSIX 系统上,time_t 以秒计量,而 difftime 等价于算术减法,但 C 和 C++ 允许小数单位的 time_t

示例

以下程序计算从月初开始经过的秒数。

#include <stdio.h>
#include <time.h>
 
int main(void)
{
    time_t now;
    time(&now);
 
    struct tm beg;
    beg = *localtime(&now);
 
    // 设 beg 为月初
    beg.tm_hour = 0;
    beg.tm_min = 0;
    beg.tm_sec = 0;
    beg.tm_mday = 1;
 
    double seconds = difftime(now, mktime(&beg));
 
    printf("%.f seconds have passed since the beginning of the month.\n", seconds);
 
    return 0;
}

输出:

1937968 seconds have passed since the beginning of the month.

引用

  • C11 standard (ISO/IEC 9899:2011):
  • 7.27.2.2 The difftime function (p: 390)
  • C99 standard (ISO/IEC 9899:1999):
  • 7.23.2.2 The difftime function (p: 339)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 4.12.2.2 The difftime function

参阅