iza*_*aak -1 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
Run Code Online (Sandbox Code Playgroud)
对于所有宏,x用函数名替换,不带参数括号.例如PRINT(foobar);等等.但是,我已经使用了多个函数名称相同的宏,因为我以为我可以代入x多次.即
START(foobar);
// later...
START(func);
Run Code Online (Sandbox Code Playgroud)
但是,我收到一个错误:
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
Run Code Online (Sandbox Code Playgroud)
一旦我用它来定义一个函数,我似乎无法重用该变量.但是,我从未在PRINT中遇到此错误.那么,是因为我在声明变量吗?
我基本上试图想出一个快速的时间戳功能,所以欢迎任何其他关于如何快速实现这一点的建议.
您需要使用宏标记连接运算符##:
#define START(x) x ## start = std::chrono::steady_clock::now()
Run Code Online (Sandbox Code Playgroud)
和其他宏类似.
当你刚写时xstart,x它不会被宏参数替换,而是xstart保持不变.参数替换仅对单个标识符进行操作; 它们不能成为更大词的一部分.