【发布时间】:2012-09-09 07:25:49
【问题描述】:
假设我想要一个适用于任何类型的 C 宏。 我正在使用 GCC 编译器 (>= 4.6) 并且可以使用 GNU99 宏。
//code...
any_type_t *retVal = function_that_runs_very_long_time(a, b, &&c, **d, &e, *f);
//other code...
TIMER 的宏用法可以是这样的
//code...
any_type_t *retVal =
TIMER(
function_that_runs_very_long_time(a, b, &&c, **d, &e, *f),
"TIMING FOR VALUE <%d, %d>", a, b
);
//other code...
因此 TIMER 必须返回给定函数的值并打印其运行的持续时间。
具有void 返回类型的函数存在问题。
我显然可以有两个宏,如 TIMER_TYPE 和 TIMER_VOID,但我想使用一个单独的函数来计时任何返回值。
感谢您的建议。
此 TIMER 宏的编辑示例
#define TIMER(expr, fmt_msg, ...) \
({ \
struct timeval before, after; \
uint64_t time_span; \
int time_span_sec, time_span_usec; \
gettimeofday(&before, NULL); \
typeof(expr) _timer_expr__ = (expr); \ // <- static if?
gettimeofday(&after, NULL); \
time_span = (after.tv_sec * 1000000 + after.tv_usec) \
- (before.tv_sec * 1000000 + before.tv_usec); \
time_span_sec = time_span / 1000000; \
time_span_usec = time_span % 1000000; \
TRACE(fmt_msg "\n%s : %d.%d seconds", \
#expr, time_span_sec, time_span_usec, ...); \
_timer_expr__; \
})
【问题讨论】:
-
我认为这在 C 中是不可能的。我在 C++ 中有一个类似的问题,它需要仅使用 C++ 的方法。如果您有兴趣,请联系this one。
-
谢谢,克里斯,但我仅限于 C(99)。在发布此问题之前,我实际上已经(不仅)阅读了您的帖子。 :)
-
宏不能“返回”值。不过,您也许可以使用逗号运算符来模拟它。
-
Joachim:你甚至可以声明 LAMBDA 宏并将其用作 qsort(arr, n, size, LAMBDA(int, (x, y) { x>y }); 即stackoverflow.com/a/3326424/64062跨度>
-
在 gcc 中使用
-finstrument-functions选项怎么样? demonstration.
标签: c types void c-preprocessor compile-time