我想知道是否可以创建一个聪明的宏来自动在 C 中运行“进程”并仅使用 C。假设我有一个像这样的小结构:
typedef struct pbench {
char description[256];
int nbenchs;
double times;
} ProcessBench;
还有一个宏(
get_time()
是一个返回双精度值的函数):
#define BENCH(process, bench_struct, description) \
int i; \
bench_struct.description = description; \
bench_struct.nbenchs = 50; \
double start = get_time(); \
for (i = 0; i < bench_struct.nbenchs; ++i) \
process(); \
bench_struct.times = get_time() - start;
如果我没记错的话,这个宏可用于使用
void func()
对带有 BENCH(func, func_bench, func_description)
签名的任何函数进行基准测试。
有没有一种方法可以创建一些像这样的宏来对
void func_args(args...)
、return_type func_return()
、return_type func_return(args...)
等函数甚至小行代码进行基准测试?
您可以只传递整个函数调用,包括参数,并忽略任何函数结果,例如
#define BENCH(process, bench_struct, description) do { \
int i; \
bench_struct.description = description; \
bench_struct.nbenchs = 50; \
double start = get_time(); \
for (i = 0; i < bench_struct.nbenchs; ++i) \
process; \
bench_struct.times = get_time() - start; \
} while (0)
BENCH(func(x, y, z), func_bench, func_description)
(请注意宏的微小变化 - 括号已从
process
中删除。)
这是另一种方法。
#define benchmark(x) for (float startTime = (float)clock() / CLOCKS_PER_SEC, run = 1.0; run == 1.0; run = 0, printf("\n%s\nTime elapsed: %fs\n", x, (float)clock() / CLOCKS_PER_SEC - startTime))
确保它在一行中或使用“\”。 像这样使用它:
benchmark("Some description")
{
///your code that you wanna measure its execution time
}