Home > Net >  How to get Unix time in C , similar to Python's "time.time()"
How to get Unix time in C , similar to Python's "time.time()"

Time:12-03

When measuring elapsed time in Python, I use the following method.

import time
startTime = time.time()
nowTime = time.time() - startTime

I think this code gets UNIX time in seconds.

time.time() returns a Float Value such as this.

>>> import time
>>> time.time()
1541317313.336098

How can I use the same measurement technique in C as in Python?

I intend to use C in a WIndows 64-bit limited environment.

CodePudding user response:

You're friend is std::chrono::steady_clock – and note: not std::chrono::system_clock as it doesn't guarantee the clock advancing monotonically (consider e.g. DST changing!).

Then you can do:

auto startTime = std::chrono::steady_clock::now();

// work of which the duration is to be measured

auto duration = std::chrono::steady_clock::now() - startTime;

The difference is a std::chrono::duration object, which you now can retrieve the relevant information from in the desired granularity, e.g. as ms:

 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();

Instead of casting, which simply cuts of the sub-units just like an integral cast cuts away the fractional part of a floating point value, rounding is possible, too.

Side note: if std::chrono::steady_clock happens to lack sufficient precision there's still std::chrono::high_resolution_clock, though it is not guaranteed that it is actually more precise than the former – and worse, might even be implemented in terms of std::system_clock (see notes there), so its use is not recommended.

CodePudding user response:

double now = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();

Go here for details.

www.epochconverter.com

  •  Tags:  
  • c
  • Related