Reputation: 658
I'm new to the chrono library and I'm trying to use it to write a function that returns how many 5 min periods there are between two times. Please note: The 1min source and 5min result period could be different so the solution needs to be flexible (e.g. 5min source, 15min result period is one possible combination).
For example, I have the following general code:
using namespace std::chrono;
using namespace std::chrono_literals;
auto tp_now = system_clock::now(); //define 1st tp
auto tp_test = tp_now - 4min; //define 2nd tp
duration<int64_t, std::ratio<1, 5*60>> five_mins; //define a duration of 5mins
std::cout << "period_index = " << floor(five_mins(tp_test)).count() << std::endl; //print out the
//period
//duration count
This code does not compile (I'm not sure why) but it hopes to display how many 5 min periods are within the 4min test period. Clearly, the 4min test period is a variable and could be different. Some examples of where the 4min variable is different with corresponding results are given below:
0-4 mins result = 0
5-9 mins result = 1
10-14 mins result = 2
15-19 mins result = 3
20-24 mins result = 4
How can I achieve this please?
Upvotes: 1
Views: 190
Reputation:
five_mins
should be a type, not a variable.
Also, std::ratio<1, 5*60>
makes for 1 three-hundredths of a second, not 5 minutes.
using five_mins = duration<int64_t, std::ratio<5*60>>;
Furthermore, since there is potential truncation happening and the time is not in floating point, you cannot use the five_mins
constructor. You HAVE to use std::chrono::duration_cast<>
, like so:
#include <chrono>
#include <iostream>
int main() {
using five_mins = std::chrono::duration<int64_t, std::ratio<5*60>>;
std::cout << std::chrono::duration_cast<five_mins>(std::chrono::seconds(700)).count() << std::endl;
}
You can see the formal details here: https://en.cppreference.com/w/cpp/chrono/duration/duration, under constructor #4.
Finally, from your original question, you still need to convert your time point into a duration to get a fully working program:
std::cout << "period_index = " << std::chrono::duration_cast<five_mins>(tp_test-tp_now).count() << std::endl
Upvotes: 6
Reputation: 16680
is there some reason you don't want to write:
std::cout << (/*some duration*/ / minutes(5)) << std::end;
See CppReference
For example, the value of minutes(14)/minutes(5)
is 2
, and the value of seconds(1000) / minutes(5)
is 3
Upvotes: 3