c++ - 调用空类方法会影响性能吗?

标签 c++ performance visual-studio-2005

定时器.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/

相关文章:

c++ - 枚举值作为 gsl::multi_span 的索引

wstring 的 C++ 句柄

asp.net-mvc - ASP.NET MVC应用程序性能分析

sql - 如何从 Reporting Services 2005 的 Count() 函数中排除空值?

.net - 在生产服务器上安装VS.NET是否安全并且可以接受?

c++ - 继承和默认构造函数

c++ - 错误信息 : non-static member found in multiple base-class subobjects of type person

performance - 寻找使用 MATLAB 计算矩阵的更快方法

python - 沿一维的 1D 数组和 3D 数组的高效乘积 - NumPy

c++ - 音频设备输入名称被截断