Is it better to store data as "60 * 60 * 24" or 86400

Viewed 157

I have a piece of code exactly:

static constexpr uint32_t secondsInADay = 60 * 60 * 24;
static constexpr uint32_t secondsInAnHour = 60 * 60;
static constexpr uint32_t secondsInAMinute = 60;

Would it be faster/efficient to store it like this:

static constexpr uint32_t secondsInADay = 86400;
static constexpr uint32_t secondsInAnHour = 3600;
static constexpr uint32_t secondsInAMinute = 60;

Or will it just be the same? Will it also use more memory?

4 Answers

Both are similar.

You can even do (to drop "magic" numbers):

static constexpr uint32_t secondsInADay =
    std::chrono::duration_cast<std::chrono::seconds>(std::chrono::days(1)).count();// C++20
//  std::chrono::duration_cast<std::chrono::seconds>(std::chrono::hours(24)).count();
static constexpr uint32_t secondsInAnHour =
    std::chrono::duration_cast<std::chrono::seconds>(std::chrono::hours(1)).count();
static constexpr uint32_t secondsInAMinute =
    std::chrono::duration_cast<std::chrono::seconds>(std::chrono::minutes(1)).count();

or

template <typename Duration>
constexpr auto numberOfSeconds(const Duration& duration)
{
    return std::chrono::duration_cast<std::chrono::seconds>(duration).count();
}

using namespace std::chrono_literals;
static constexpr uint32_t secondsInADay = numberOfSeconds(24h);
                               // = numberOfSeconds(std::chrono::days(1));// C++20
static constexpr uint32_t secondsInAnHour = numberOfSeconds(1h);
static constexpr uint32_t secondsInAMinute = numberOfSeconds(1m);

Your constants are completely hardcoded, i.e. you assign them an explicit value in the code, which allows the compiler to compute the value at compile time.

60*60*24 is exactly the same as 86400

if you declare variables as:

uint32_t a = 60*60*24;
uint32_t b = 86400;

the assembly will have the following definitions:

a:
        .long   86400
b:
        .long   86400

tested with gcc.

There are same. The expression will be calculated by compiler.

Please use the first one because it has more meaning.

They're the same. There won't be any performance change because you declared them constexpr. They will, therefore, be computed during the compilation and replaced by their exact values in the assembly code.

Related