10

I have a Python program and a C++ program. They communicate via IPC.

The Python will send a JSON {"event_time":time.time()} to C++ program.

The C++ program will record this time, and insert the event into its own event queue according to the time sent via Python. I need operations such as comparison and subtraction of two time values from Python and c++.

Python's time.time() is a simple double number that can be compared and sorted easily (e.g., it is something like 1428657539.065105).

Is there anything equivalent in C++ to this value? They should at least agree to the number in accuracy of millisecond but not second? I.e., if I execute the two programs in the same time, they should get the same value in seconds and minor difference in the millisecond range.

If not, then I have to fall back to use the YEAR, MONTH, DAY, HOUR, MIN, SEC, MILLISECOND strategy. The comparison, subtraction between two time values etc. will be harder than double comparison and double subtraction.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
user534498
  • 3,926
  • 5
  • 27
  • 52
  • 5
    http://stackoverflow.com/questions/19555121/how-to-get-current-timestamp-in-milliseconds-since-1970-just-the-way-java-gets – deviantfan Apr 10 '15 at 09:44
  • 2
    Thanks. I've tried. They return almost the same value even in microseconds range. It's not a problem. It's exactly what I need. – user534498 Apr 10 '15 at 10:06

1 Answers1

4

To get the current time since the epoch in seconds as a floating-point value, you can duration_cast to a floating-point duration type:

#include <chrono>

double fractional_seconds_since_epoch
    = std::chrono::duration_cast<std::chrono::duration<double>>(
        std::chrono::system_clock::now().time_since_epoch()).count();
benathon
  • 7,455
  • 2
  • 41
  • 70
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • Visual Studio 2019 if you include above it will build, but on the editor it appears as an error. (the squiggly underline) – lkreinitz Oct 24 '20 at 15:45