次のように私は(私の.h
ファイルで指定され、実装されている)2つのインライン関数を使用することにより、総経過時間を収集しています:Cで処理時間を収集する方法は?
extern double _elapsed_time_mf;
extern double _elapsed_time_b;
//this function returns the elapsed time in order to compute the total elapsed time of an operation
static inline struct timeval get_current_time() {
struct timeval time;
gettimeofday(&time, NULL);
return time;
}
//calculate the total processed time and return the elapsed total time in seconds
static inline double get_elapsed_time(struct timeval start, struct timeval end) {
long int tmili;
tmili = (int) (1000.0 * (end.tv_sec - start.tv_sec) +
(end.tv_usec - start.tv_usec)/1000.0);
return (double) (tmili/(double) 1000.0);
}
その後、私は私が行う操作の合計経過時間を知りたいの際これは:
void my_function() {
#ifdef COLLECT_STATISTICAL_DATA
struct timeval start;
struct timeval end;
start = get_current_time();
#endif
//a processing....
#ifdef COLLECT_STATISTICAL_DATA
end = get_current_time();
_elapsed_time_mf = get_elapsed_time(start, end);
#endif
}
_elapsed_time_mf
一つだけ.c
ファイルで定義されています。
しかし、私は奇妙な結果を得ています。たとえば、function_b
という別の関数があるとします。この関数は経過時間(他のグローバル変数に格納されています)も収集します。次に、この関数はmy_function
(前のコードに従って経過時間を収集する)を呼び出します。ただし、合計経過時間がfunction_b
の場合は、my_functionの合計経過時間よりも小さい場合があります。このような状況の例は次のとおりです。たまに
void function_b() {
#ifdef COLLECT_STATISTICAL_DATA
struct timeval start;
struct timeval end;
start = get_current_time();
#endif
//a processing....
my_function();
//another processing...
#ifdef COLLECT_STATISTICAL_DATA
end = get_current_time();
_elapsed_time_b = get_elapsed_time(start, end);
#endif
}
_elapsed_time_b
は_elapsed_time_mf
よりも低いです。どうして? クロック/日付/タイムスタンプ(CPU経過時間ではありません)に従って経過時間を秒単位で収集したいと思います。
'gettimeofday'はタイミング情報を収集するための非常に悪いです:
私の機能は今のように記述されています。それは静的な周波数を持たず、いくつかのシステム/構成では逆方向に進むことができます。これはあなたの場合に起こることではありませんが、心に留めておく価値があります。 – Art
@Artあなたは何をお勧めしますか? –
'clock_gettime'と' CLOCK_MONOTONIC'を最小限に抑えて(単調な時計の更新以上を保証するシステム特有の改善があります)、システムにそれがない場合は、少なくとも保証されないより良い時間関数を見てください後方に。 'gettimeofday'は、後ろに行く、前に飛ぶ、周波数を変更するなどの理由で、最悪のケースです。 – Art