C++ 中的 difftime() 函数


在本文中,我们将讨论 C++ 中的 difftime() 函数、其语法、工作原理及其返回值。

difftime() 函数是 C++ 中的内置函数,定义在头文件中。该函数接受两个 time_t 类型的参数,函数计算两个时间之间的差值

语法

double difftime(time_t end, time_t beginning);

返回值

以双精度数据类型存储的时间差(秒)。

示例

 实时演示

#include <stdio.h>
#include <time.h>
int main () {
   time_t now;
   struct tm newyear;
   double seconds;
   time(&now); /* get current time; */
   newyear = *localtime(&now);
   newyear.tm_hour = 0; newyear.tm_min = 0; newyear.tm_sec = 0;
   newyear.tm_mon = 0; newyear.tm_mday = 1;
   seconds = difftime(now,mktime(&newyear));
   printf ("%.f seconds since new year in the current timezone.\n", seconds);
   return 0;
}

输出

如果我们运行以上代码,它将生成以下输出 −

3351041 seconds since new year in the current timezone.

示例

#include <iostream>
#include <ctime>
using namespace std;
int main() {
   time_t start, ending;
   long addition;
   time(&start);
   for (int i = 0;
   i < 50000; i++) {
      for (int j = 0; j < 50000; j++);
   }
   for (int i = 0; i < 50000; i++) {
      for (int j = 0; j < 50000; j++);
   } for (int i = 0; i < 50000; i++) {
      for (int j = 0; j < 50000; j++);
   } time(&ending);
   cout << "Total time required = " << difftime(ending, start) << " seconds " << endl;
   return 0;
}

输出

如果我们运行以上代码,它将生成以下输出 −

Total time required = 37 seconds

更新于: 28-2-2020

169 次浏览

开启你的 职业生涯

完成课程获得认证

立即开始
广告
© . All rights reserved.