C++ 中的 difftime() 函数

c++server side programmingprogramming更新于 2024/11/10 20:13:00

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

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

语法

double difftime(time_t end, time_t beginning);

返回值

返回以秒为单位的时间差异,存储为 double 数据类型。

示例

#include <stdio.h>
#include <time.h>
int main () {
   time_t now;
   struct tm newyear;
   double seconds;
   time(&now); /* 获取当前时间; */
   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

相关文章