定时器.h:
class Timer
{
public:
void start();
void printTimeAndRestart(const char* msg);
};
namespace Timing { static Timer timer; }
定时器.cpp:
#ifdef DO_TIMING
//implementation
void Timer::start() { ... };
void Timer::printTimeAndRestart(const char* msg) { ... };
#else
//empty - do not do timing
void Timer::start() {};
void Timer::printTimeAndRestart(const char* /*msg*/) {};
#endif
计时器将在许多不同的文件中使用,例如:
Timing::timer.start();
...
Timing::timer.printTimeAndRestart("Operation X took :");
如果应用程序对性能非常敏感并且经常调用计时器,那么在未定义 DO_TIMING 时调用空方法会影响性能吗?实现隔离定时器(无需重新编译整个项目来打开/关闭)的更好选择是什么,关闭时根本不影响性能。
到目前为止,我只能想到定义像这样的宏
#ifdef DO_TIMING
#define START_TIMING()
Timing::timer.start();
#endif
#else
#define START_TIMING()
#endif
并使用它们代替 Timing::timer.start();但这需要重新编译整个代码才能打开/关闭它们......
最佳答案
这取决于你如何使用它。如果它是相同的项目/解决方案并且编译器能够进行完整的程序优化,那么它可能是无关紧要的。
如果您使用二进制文件分发代码并且实现不可见,并且编译器无法判断它是空的,则由于调用会产生一些(较小的)开销。
关于c++ - 调用空类方法会影响性能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15552296/