Home > OS >  converting (roughly) the current time into a 32 bit integer
converting (roughly) the current time into a 32 bit integer

Time:10-07

I just need a way to roughly convert current time into a 32 bit integer. It doesn't need to be very accurate.. even accuracy of only a couple minutes would be ok.

The main idea is the next time I need to check it, it should be higher than or at least not lower than the previous time I retrieved this value. (I don't check very often)

I use C 20 (the MSVC version of it, whatever comes with VS 2022)

CodePudding user response:

Using the C standard library - which is also part of the C standard library - you can use std::time()

The example in cppreference gives:

    std::time_t result = std::time(nullptr);
    std::cout << std::asctime(std::localtime(&result))
              << result << " seconds since the Epoch\n";

Resulting in

Thu Oct  6 16:16:31 2022
1665072991 seconds since the Epoch

Godbolt: https://godbolt.org/z/v1aE9rjfs

HOWEVER this time CAN warp back, meaning that you can get a number later that is smaller than the current one.

What you can do is to use std::chrono::steady_clock.

But if you do not mind being specific to clang and gcc and Intel, you can use a builtin to read the TSC counter to get a simple and super fast solution

uint64_t now64 = __builtin_ia32_rdtsc();
uint32_t now = now64 >> 20;

Using the right 20 shift will give you one tick at roughly 3 milliseconds. Note this counter will roll over in about 150 days.

  •  Tags:  
  • c
  • Related