我有一个ASSERT(...)
在 C++ 应用程序中使用的自定义宏。
#include <stdlib.h>
#include <iostream>
/// ASSERT(expr) checks if expr is true. If not, error details are logged
/// and the process is exited with a non-zero code.
#ifdef INCLUDE_ASSERTIONS
#define ASSERT(expr) \
if (!(expr)) { \
char buf[4096]; \
snprintf (buf, 4096, "Assertion failed in \"%s\", line %d\n%s\n", \
__FILE__, __LINE__, #expr); \
std::cerr << buf; \
::abort(); \
} \
else // This 'else' exists to catch the user's following semicolon
#else
#define ASSERT(expr)
#endif
最近在看一些Linux内核模块代码,偶然发现了宏的likely(...)
存在unlikely(...)
。这些向 CPU 提供了一个提示,即给定分支更有可能,并且管道应该针对该路径进行优化。
根据定义,断言的计算结果为真(即likely
)。
我可以在我的ASSERT
宏中提供类似的提示吗?这里的底层机制是什么?
显然我会测量性能上的任何差异,但理论上它应该有什么不同吗?
我只在 Linux 上运行我的代码,但很想知道是否也有跨平台的方式来执行此操作。我也在使用 gcc,但也想支持 clang。