4

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) 
5
  • 3
    Well, you could start a timer, then use a normal assertion that the total is less than whatever your limit is. Commented Jan 20, 2017 at 10:43
  • 2
    Do note that assert is a macro that does nothing on typical release builds (when NDEBUG is defined). Commented Jan 20, 2017 at 10:43
  • 1
    Not in the language or the standard library; That said, they are (almost) trivial to write. Commented Jan 20, 2017 at 10:46
  • 3
    tick = clock(); function(); tock = clock(); assert(tock - tick < PERFORMANCE); Commented Jan 20, 2017 at 10:48
  • 3
    Please pick one language. C and C++ differ completely here. Commented Jan 20, 2017 at 11:21

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.