我通过使用两个内联函数(在我的.h
文件中指定并实现)来收集总耗用时间,如下所示:
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经过时间)收集两次经过的时间。
答案 0 :(得分:0)
您可能想重新考虑get_elapsed_time的实现。从这里开始:http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html
int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
答案 1 :(得分:0)
正如Art评论的那样,我现在正在使用clock_gettime。因此,我的代码现在按预期工作。
我的功能现在写成:
static inline double get_elapsed_time(struct timespec start, struct timespec end) {
double start_in_sec = (double)start.tv_sec + (double)start.tv_nsec / 1000000000.0;
double end_in_sec = (double)end.tv_sec + (double)end.tv_nsec / 1000000000.0;
return end_in_sec - start_in_sec;
}
static inline struct timespec get_current_time() {
struct timespec time;
clock_gettime(CLOCK_MONOTONIC, &time);
return time;
}