Difftime() C 库函数

c++server side programmingprogramming

这里我们将了解 C 中的 difftime() 函数是什么。difftime() 用于获取两个时间值之间的差异。

difftime() 接受两个时间参数,第一个是下限,第二个是上限。它返回这两个参数之间的差异。

示例

#include <time.h>
#include <stdio.h>
#include <unistd.h>
main() {
   int sec;
   time_t time1, time2;
   time(&time1);
   printf("Current Time: %ld\n",time1);
   for (sec = 1; sec <= 5; sec++){
      sleep(1);
      printf("Count: %d\n",sec);
   }
   time(&time2);
   printf("Ending Time: %ld\n",time2);
   printf("Difference is %.2f seconds", difftime(time2, time1));
}

输出

Current Time: 1554918635
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Ending Time: 1554918640
Difference is 5.00 seconds

相关文章