-1

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.

Botje
  • 26,269
  • 3
  • 31
  • 41
taichi
  • 631
  • 1
  • 7
  • 26
  • 2
    Step 1: Consult [the documentation](https://en.cppreference.com/w/cpp/chrono). – tadman Dec 02 '22 at 14:18
  • https://stackoverflow.com/a/6012671/20002417 This is a very similiar question with a really good answer. – h4yv3n Dec 02 '22 at 14:21
  • More precisely: [getting current time](https://en.cppreference.com/w/cpp/chrono/system_clock/now) and [getting unix timestamp from](https://en.cppreference.com/w/cpp/chrono/time_point/time_since_epoch). And when peeking into first link: The example there is actually a bad one, for measuring time periods `system_clock` is not suitable as time might jump (e.g. due to DST changing); use `steady_clock` for such purposes instead! – Aconcagua Dec 02 '22 at 14:23
  • Just to make it clear: since you're measuring a time **duration**, the **epoch** doesn't matter. "Unix time" is a shorthand for "time, with an epoch of 1-1-1970". These 1970 years cancel out in the `current_time - start_time` subtraction. If if you used 1CE as the epoch, that would cancel out the same. – MSalters Dec 02 '22 at 14:31

2 Answers2

2

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 off 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.

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
0
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

DevSolar
  • 67,862
  • 21
  • 134
  • 209
Ram
  • 1,225
  • 2
  • 24
  • 48