简体   繁体   English

性能断言

[英]Performance assertions

I know that C supports functional assertions using assert() . 我知道C使用assert()支持函数断言。 Is there any way/library supporting performance assertions in C/C++? 是否有任何方式/库支持C / C ++中的性能断言? Is there in any other languages? 有其他语言吗?

Something along the lines of the following: 以下内容:

perf_assert_begin(ID1)
...
...
/* assert the time taken is less than 2000 ms */
perf_assert_end(ID1, interval(ID1) < 2000)

Assertion can be done using either assert from <cassert> or static_assert , which is built into the language. 可以使用<cassert> assert或内置于语言中的static_assert来完成assert
So, why not take the time manually and then check the time difference in an assert statement? 那么,为什么不手动花时间检查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

The preprocessor directives let the code only pass through to the compiler if NDEBUG is defined. 如果定义了NDEBUG ,预处理程序指令只允许代码传递给编译器。 assert only takes action if NDEBUG is defined too and one without the other doesn't work very well. 如果定义了NDEBUGassert仅执行操作,而没有其他的则不能正常工作。

To prevent name clashes when NDEBUG is defined with the start identifier, you might do some GCC-magic with __COUNTER__ to make the identifier unique (compiler-specific) or move the whole thing into a separate scope. 为了防止在使用start标识符定义NDEBUG时发生名称冲突,您可以使用__COUNTER__执行一些GCC-magic以使标识符唯一(特定于编译器)或将整个内容移动到单独的范围中。 It might be a non-issue to you, but some people might be surprised by a conditionally-defined variable if they look at your program from a certain perspective. 这对你来说可能不是问题,但是如果从某个角度看你的程序,有些人可能会对条件定义的变量感到惊讶。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM