我知道 C 支持使用 assert()
的函数式断言。有没有什么方法/库支持 C/C++ 中的性能断言?有其他语言吗?
大致如下:
perf_assert_begin(ID1)
...
...
/* assert the time taken is less than 2000 ms */
perf_assert_end(ID1, interval(ID1) < 2000)
最佳答案
断言可以使用 assert
来完成来自 <cassert>
或 static_assert
,它内置于语言中。
那么,为什么不手动计时然后检查 assert
中的时差呢?声明?
#include <cassert>
#include <chrono>
#ifndef NDEBUG
auto start = std::chrono::high_resolution_clock::now();
#endif
...
#ifndef NDEBUG
assert(std::chrono::duration_cast<milliseconds>(
std::chrono::high_resolution_clock::now() - start).count() < 2000
);
#endif
如果NDEBUG
,预处理器指令让代码只通过编译器。被定义为。 assert
仅在 NDEBUG
时才采取行动也被定义,一个没有另一个不能很好地工作。
为了防止在 NDEBUG
时发生名称冲突用 start
定义标识符,你可以用 __COUNTER__
做一些 GCC 魔法使标识符唯一(特定于编译器)或将整个事物移动到一个单独的范围内。这对您来说可能不是问题,但如果某些人从某个角度看您的程序,他们可能会对条件定义的变量感到惊讶。
关于c++ - 性能断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41761651/