プログラムまたは関数の実行にかかった時間を秒単位で求める C プログラム

  • C でプログラムを作成して、プログラムの実行時間を秒単位で計算する
  • C で関数またはステートメントの実行にかかる時間を調べる方法
C プログラムの実行時間を調べるには 、time.hヘッダーファイルのclock()関数を使用します。
  • clock() 関数は、プログラムが開始されてから経過したクロック ティック数を返します。
  • プログラムの合計実行時間を調べるには、クロック関数を 2 回呼び出します。1 回目は main 関数の開始時、2 回目は main 関数の終了時です。
  • ここで、プログラムの合計実行時間 (CPU クロック ティックの単位) は、これら 2 つの時間インスタンスの差です。
  • 実行時間を秒単位で取得するには、差を CLOCKS_PER_SEC (1 秒あたりのクロック ティック数) で割る必要があります。
C プログラムの実行時間を確認するための clock() 関数の配置
# include<stdio.h>
# include<time.h>

int main() {
clock_t start, end;
double execution_time;
start = clock();

/* Put your code here */

end = clock();
execution_time = ((double)(end - start))/CLOCKS_PER_SEC;

プログラムの実行時間を見つける C プログラム

#include <stdio.h>
#include <time.h>

int main() {
    clock_t start, end;
    /* Store start time here */
    start = clock();
    /* put the main body of your program here */
    printf("Enter any character\n");
    getchar();
    /* program logic ends here */
    end = clock();
    /* Get the time taken by program to execute in seconds */
    double duration = ((double)end - start)/CLOCKS_PER_SEC;
    
    printf("Time taken to execute in seconds : %f", duration);
    return 0;
}
出力
Enter any character
d
Time taken to execute in seconds : 2.371000

関数の実行時間を見つけるための C プログラムn

#include <stdio.h>
#include <time.h>

void my_function(){
    /* Body of function */
    float f;
    for(f=0.0; f<1000000; f=f+1.0);
}
int main() {
    clock_t start, end;
    /* Store time before function call */
    start = clock();
    my_function();
    /* Store time after function call */
    end = clock();
    /* Get the time taken by program to execute in seconds */
    double duration = ((double)end - start)/CLOCKS_PER_SEC;
    
    printf("Time taken to execute in seconds : %f", duration);
    return 0;
}
出力
Time taken to execute in seconds : 0.015000