Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return next full second based on current time

I am trying to create a function that will return next full second, but looking through the c++11 std::chrono documentation I cannot find any obvious way to accomplish that.

Example: If the current time is 09:50:01.1234 I want the function to return 09:50:02.0000(i.e. the next full second).

std::chrono::system_clock::time_point return_next_full_second()
{
    using namespace std::chrono;
    system_clock::time_point now = system_clock::now();

    system_clock::time_point next_full_second = // How? 

    return next_full_second;
}

Any hints on how to accomplish this, if at all possible using std::chrono ?

My goal I want to achieve is to perform a specific action, at as close to every full second as possible. So I will be using the result to sleep for a duration of return_next_full_second() - system_clock::now().

like image 895
Bjarke Freund-Hansen Avatar asked Oct 29 '25 18:10

Bjarke Freund-Hansen


1 Answers

You might do a duration cast to seconds:

#include <chrono>
#include <iostream>

std::chrono::system_clock::time_point return_next_full_second()
{
    using namespace std::chrono;
    system_clock::time_point now = system_clock::now();
    auto s = duration_cast<seconds>(now.time_since_epoch());
    return system_clock::time_point(++s);
}

int main() {
    using namespace std::chrono;
    auto t = return_next_full_second();
    auto d = duration_cast<milliseconds>(t.time_since_epoch());
    std::cout <<  d.count() << '\n';
}