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.