重用宏变量

时间:2016-05-24 15:14:25

标签: c++ macros c-preprocessor

我正在尝试对大量函数进行基准测试,并且我已经定义了宏来概括时间戳。我已经制作了一个头文件benchmark,如下:

#include <chrono> 
#include <iostream>

#define START(x) xstart = std::chrono::steady_clock::now()                                         
#define END(x)   xend   = std::chrono::steady_clock::now()                                         
#define TIME(x)  xtime  = std::chrono::duration_cast<std::chrono::nanoseconds>(xend-xstart).count()
#define PRINT(x) std::cout << #x << "(), " << xtime << std::endl

对于所有宏,x用函数名替换,不带参数括号。例如PRINT(foobar);等 但是,我已经为多个函数名使用了相同的宏,因为我认为我可以多次替换x。 即。

START(foobar);
// later...
START(func);

然而,我收到错误:

xstart’ has a previous declaration as ‘std::chrono::time_point<std::chrono::_V2::steady_clock, std::chrono::duration\<long int, std::ratio<1l, 1000000000l> > > xstart

一旦我用它来定义一个函数,我似乎无法重用该变量。 但是,我从未在PRINT中遇到此错误。那么,是因为我在声明变量吗?

我基本上试图想出一种快速的时间戳功能,所以欢迎任何有关如何快速实现这一目标的建议。

1 个答案:

答案 0 :(得分:5)

您需要使用宏标记并置运算符##

#define START(x) x ## start = std::chrono::steady_clock::now()

和其他宏类似。

当您只写xstart时,x不会被宏参数替换,但xstart保持不变。参数替换仅对单个标识符进行操作;它们不能成为更大词的一部分。

相关问题