GabiMe
GabiMe

Reputation: 18473

C++11: constexpr constructor performance

I got little confused with constepxt ctors..

Does the following is as just as fast (or faster)

while(true)
{
   constexpr std::chrono::hours one_hour(1);
   ..
}

than (creating only one instance):

while(true)
{
   static constexpr std::chrono::hours one_hour(1);
   ..
}

In other words, Does constexpr ctor means no runtime overhead whatsoever?

Upvotes: 3

Views: 463

Answers (2)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136256

Adding constexpr here won't make much difference because std::chrono durations and time points contain only a single integer member. In other words. the performance of initialization is the same as of int.

Upvotes: 1

Ali
Ali

Reputation: 58461

Does constexpr ctor means no runtime overhead whatsoever?

When in doubt, you can always check; for example:

#include <chrono>

template <long Long>
class dummy { };

int main() {

  constexpr std::chrono::hours one_hour(1);

  dummy<one_hour.count()> d; 
}

The fact that it compiles means that one_hour is a compile time constant and as such, has no runtime overhead whatsoever.

Upvotes: 8

Related Questions