ホームページ  >  記事  >  バックエンド開発  >  C で関数の実行時間を測定するにはどうすればよいですか?

C で関数の実行時間を測定するにはどうすればよいですか?

WBOY
WBOY転載
2023-08-28 14:21:06967ブラウズ

C で関数の実行時間を測定するにはどうすればよいですか?

ここでは、プロセスにかかる時間を計算する方法を見ていきます。この問題には、 Clock() 関数を使用します。 Clock() 関数は time.h ヘッダー ファイルにあります。

経過時間を取得するには、 Clock() を使用してタスクの開始時の時間を取得し、再度 Clock() を使用してタスクの終了時の時間を取得し、その 2 つを減算します。違いを得るために値を設定します。次に、その差を CLOCK_PER_SEC (1 秒あたりのクロック数) で割って、プロセッサ時間を取得します。

#include <stdio.h>
#include <time.h>
void take_enter() {
   printf("Press enter to stop the counter </p><p>");
   while(1) {
      if (getchar())
      break;
   }
}
main() {
   // Calculate the time taken by take_enter()
   clock_t t;
   t = clock();
   printf("Timer starts</p><p>");
   take_enter();
   printf("Timer ends </p><p>");
   t = clock() - t;
   double time_taken = ((double)t)/CLOCKS_PER_SEC; // calculate the elapsed time
   printf("The program took %f seconds to execute", time_taken);
}

出力

Timer starts
Press enter to stop the counter
Timer ends
The program took 5.218000 seconds to execute

以上がC で関数の実行時間を測定するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。