简体   繁体   中英

std::chrono, adding duration to time_point

I am trying to add some duration to a time_point in Qt (C++11/MinGW) and I am having trouble:

Initialization (when the program starts):

auto program_start_time = std::chrono::system_clock::now();
auto offline_time = std::chrono::system_clock::now();

...

Some activity goes offline:

offline_mark_time = std::chrono::system_clock::now();

...

When the activity resumes, I need to add the offline time to my start time:

auto now = std::chrono::system_clock::now();
program_start_time += (now - offline_mark_time);  // <- Does not seem to work

Even though compilation and executions is ok, the program's behavior is as if I am adding zero.

How do you add or subtract a duration to a time_point?

This complete program, based on the snippets of code in your answer:

#include <iostream>
#include <thread>
#include <chrono>

int
main()
{
    auto program_start_time = std::chrono::system_clock::now();
    auto copy_of_program_start_time = program_start_time;
    auto offline_mark_time = std::chrono::system_clock::now();
    std::this_thread::sleep_for(std::chrono::microseconds(100));
    auto now = std::chrono::system_clock::now();
    program_start_time += (now - offline_mark_time);
    std::cout << (program_start_time > copy_of_program_start_time) << '\n';
}

for me prints out:

1

If the time duration between the construction of offline_mark_time and now is less than than the precision of system_clock::duration (1 microsecond for me), then now and offline_mark_time will likely be equal and thus 0 would be added to program_start_time in that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM