tomol
tomol

Reputation: 763

Performance assertions

I know that C supports functional assertions using assert(). Is there any way/library supporting performance assertions in 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)

Upvotes: 4

Views: 786

Answers (1)

cadaniluk
cadaniluk

Reputation: 15229

Assertion can be done using either assert from <cassert> or static_assert, which is built into the language.
So, why not take the time manually and then check the time difference in an assert statement?

#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. assert only takes action if NDEBUG is defined too and one without the other doesn't work very well.

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. 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.

Upvotes: 1

Related Questions