2016-09-18 22 views
3

私はプログラムの実行時間をタイムヘッダーを使用して取得しようとしていますが、<time.h>ではなく<sys/time.h>を使用するリソースは見つかりません。時間が整数であると私のプロセスは秒未満を要するためC - プログラムの実行時間(ミリ秒単位)<time.h>

私は

time_t startTime;     
time_t endTime;     
long double execTime;   

/* Start timer */ 
time(&startTime); 

..STUFF THAT TAKES TIME.. 

time(&endTime); 
execTime = difftime(endTime, startTime); 

printf("Computing took %Lf\n", execTime * 1000); 

を試してみました。しかし、これは0に一つ一つの時間を出力します..私は推測しています。

実行をミリ秒単位で表示するにはどうすればよいですか?

time機能がわずか1秒の分解能を持っているあなたに

答えて

3

clock_gettimeが好ましい方法である必要がありますが、それはPOSIXのではなく、標準のCであります彼らはclockしか持っていません。それには多くの欠点がありますが、迅速で汚れた測定には十分です。

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

int main() 
{ 
    int i, j, a[1000000] = { 0 }; 
    clock_t start, stop; 
    srand(0xdeadbeef); 
    start = clock(); 
    // play around with these values, especially with j 
    for (j = 0; j < 100; j++) { 
    for (i = 0; i < 1000000; i++) { 
     a[i] = rand() % 123; 
     a[i] += 123; 
    } 
    } 
    stop = clock(); 
    printf("Time %.10f seconds\n", (double) (stop - start)/CLOCKS_PER_SEC); 
    exit(EXIT_SUCCESS); 
} 
+0

パーフェクト。私はミリ秒を得るために出力を1000倍して、私は良いです。 – Walker

+0

MSVCの 'clock'実装は** wall time **に[here here](https://msdn.microsoft.com/en-us/library/4e2ess30.aspx)を与えていますが、 –

+0

@deamentiaemundiこれはオンラインのコンパイラですが、教授がそれをコンパイルするサーバに持ち込んだら毎回0.000ミリ秒を返します。奇妙な – Walker

1

ありがとうございます。代わりに、マイクロ秒の解像度を持つgettimeofdayを使用してください。

struct timeval tstart, tend; 
gettimeofday(&tstart, NULL); 
// do something that takes time 
gettimeofday(&tend,NULL); 
+1

サンプルを提供してもよろしいですか?ありがとうございます。 – Walker

+0

'gettimeofday'は時差の測定に使用しないでください。もっと知りたいのであれば、 'clock_gettime(CLOCK_MONOTONIC、&ts_current);'を使ってください。[これをチェックしてください](https://blog.habets.se/2010/09/gettimeofday-should-never-be-used- to-measure-time) –

+0

'gettimeofday'はUNIX特有のものです。速くて汚い移植可能な解決策のために' clock() 'を使います。 – chqrlie

2

時間を測定する正しい方法は、clock_gettime(CLOCK_MONOTONIC, &ts_current);を使用することです。

また、gettimeofday() should be avoided

時間差を測定するclock_gettime()を使用しての完全な例(秒およびナノ秒の両方、あなたはミリ秒に変換することができる):

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

struct timespec diff(struct timespec start, struct timespec end) 
{ 
    struct timespec temp; 
    if ((end.tv_nsec-start.tv_nsec)<0) { 
     temp.tv_sec = end.tv_sec-start.tv_sec-1; 
     temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; 
    } else { 
     temp.tv_sec = end.tv_sec-start.tv_sec; 
     temp.tv_nsec = end.tv_nsec-start.tv_nsec; 
    } 
    return temp; 
} 

int main() 
{ 
    struct timespec time1, time2; 
    int temp = 0; 
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1); 
    for (int i = 0; i< 242000000; i++) 
     temp+=temp; 
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2); 
    printf("Time difference: %ld [s] %ld [ns]", (long) diff(time1,time2).tv_sec, (long) diff(time1,time2).tv_nsec); 
    return 0; 
} 
+0

'clock_gettime()'はMac OS Xでは利用できないので、 'gettimeofday()'ほど移植性がありません。 –

関連する問題