Multiply std::chrono timepoint by a scalar - c++

How can one multiply a chrono timepoint by a scalar? It works for durations, but timepoints can't be multiplied by a scalar ("error: invalid operands to binary expression").
Context:
I have some code that in real life will run for a long time. For testing purposes, I want to be able to speed it up by a factor, so everything happens similarly, but just in fast forward.
I thought of making my own ScaledClock class, that returns values from chrono::steady_clock, but with a scaling parameter that can be set to something greater than 1 to achieve a speed up. Here is some code:
steady_clock::time_point ScaledClock::now() {
return steady_clock::now() * speedUp; // <--- error
}
void ScaledClock::sleep_for(steady_clock::duration duration) {
std::this_thread::sleep_for(duration / speedUp);
}
void ScaledClock::sleep_until(steady_clock::time_point time) {
std::this_thread::sleep_until(time / speedUp); // <--- error
}
If the speedUp is 2, for instance, then the program will always think that twice as much time has passed. It will also sleep for half as long. As long as I am disciplined about not using this class for all timing, I think it should work.
(Alternatively, if someone has a much better way of achieving this, I'd love to hear it).
Edit: copy of comment, because I think it is useful clarification:
en.cppreference.com/w/cpp/chrono/time_point:
Class template std::chrono::time_point represents a point in time. It
is implemented as if it stores a value of type Duration indicating the
time interval from the start of the Clock's epoch.
So I want all the times since the epoch doubled. If the epoch is not start of program execution, and my code happens to think that it is running in 4036, I'm not really bothered

You will need to store a starting point (now() e.g. at program start) and then determine the time passed since that starting point as a duration. You can then add this duration multiplied with your factor to the start point and return it as time point in your ScaledClock::now() function. Just like this:
#include <chrono>
#include <unistd.h>
int main() {
auto start = std::chrono::steady_clock::now();
sleep(1);
auto actualNow = std::chrono::steady_clock::now();
auto timePassed = actualNow - start;
auto timePassedScaled = timePassed * 2.0;
auto scaledNow = start + timePassedScaled;
return 0;
}

Related

How do I create a timer that I can query during the program and whose format is int, long or double?

I want to start a clock at the beginning of my program and use its elapsed time during the program to do some calculations, so the time should be in a int, long or double format. For example i want to calculate a debounce time but when i try it like this i get errors because the chrono high resolution clock is not in an int, long or double format and therefore i can't subtract 50ms from that (my debounceDelay) or save that value to a double (my lastDebounceTime). Originally i had a working Arduino Game (Pong) with an LCD and i want to convert this into a C++ console application.
On the Arduino there was this function "millis()" that gave me the runtime in ms and this worked perfectly fine. I can't find a similar function for C++.
double lastDebounceTime = 0;
double debounceDelay = 50;
void Player1Pos() {
if ((std::chrono::high_resolution_clock::now() - lastDebounceTime) > debounceDelay) {
if ((GetKeyState('A') & 0x8000) && (Player1Position == 0)) {
Player1Position = 1;
lastDebounceTime = std::chrono::high_resolution_clock::now();
}
else if ((GetKeyState('A') & 0x8000) && (Player1Position == 1)) {
Player1Position = 0;
lastDebounceTime = std::chrono::high_resolution_clock::now();
}
}
I am very new to C++ so any help is greatly appreciated.
Thank you all!
I find the question misguided in its attempt to force the answer to use "int, long, or double". Those are not appropriate types for the task at hand. For references, see A: Cast chrono::milliseconds to uint64_t? and A: C++ chrono - get duration as float or long long. The question should have asked about obtaining the desired functionality (whatever the code block is supposed to do), rather than asking about a pre-chosen approach to the desired functionality. So that is what I will answer first.
Getting the desired result
To get the code block to compile, you just have to drop the insistence that the variables be "int, long, or double". Instead, use time-oriented types for time-oriented data. Here are the first two variables in the code block:
double lastDebounceTime = 0;
double debounceDelay = 50;
The first is supposed to represent a point in time, and the second a time duration. The C++ type for representing a point in time is std::chrono::time_point, and the C++ type for a time duration is a std::chrono::duration. Almost. Technically, these are not types, but type templates. To get actual types, some template arguments need to be supplied. Fortunately, we can get the compiler to synthesize the arguments for us.
The following code block compiles. You might note that I left out details that I consider irrelevant to the question at hand, hence that I feel should have been left out of the minimal reproducible example. Take this as an example of how to simplify code when asking questions in the future.
// Use the <chrono> library when measuring time
#include <chrono>
// Enable use of the `ms` suffix.
using namespace std::chrono_literals;
std::chrono::high_resolution_clock::time_point lastDebounceTime;
// Alternatively, if the initialization to zero is not crucial:
// auto lastDebounceTime = std::chrono::high_resolution_clock::now();
auto debounceDelay = 50ms;
void Player1Pos() {
if ((std::chrono::high_resolution_clock::now() - lastDebounceTime) > debounceDelay) {
// Do stuff
lastDebounceTime = std::chrono::high_resolution_clock::now();
}
}
Subtracting two time_points produces a duration, which can be compared to another duration. The logic works and now is type-safe.
Getting the desired approach
OK, back to the question that was actually asked. You can convert the value returned by now() to an arithmetic type (integer or floating point) with the following code. You should doubts about using this code after reading the comment that goes with it.
// Get the number of [some time units] since [some special time].
std::chrono::high_resolution_clock::now().time_since_epoch().count();
The time units involved are not specified by the standard, but are instead whatever std::chrono::high_resolution_clock::period corresponds to, not necessarily milliseconds. The special time is called the clock's epoch, which could be anything. Fortunately for your use case, the exact epoch does not matter – you just need it to be constant for each run of the program, which it is. However, the unknown units could be a problem, requiring more code to handle correctly.
I find the appropriate types easier to use than trying to get this conversion correct. Especially since it required no change to your function.

comparing against time with chrono c++

I want to pretty much say "as long as we are under a certain time, continue to iterate"
the code for this looks like
int time = atoi(argv[1]);
auto start = std::chrono::high_resolution_clock::now();
while((std::chrono::duration_cast<chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start).count()) < time){
/*perform operation*/
}
However I am unable to compare against time like this and get the error error: conversion to ‘double’ from ‘std::chrono::duration<long int, std::ratio<1, 1000> >::rep {aka long int}’ may alter its value [-Werror=conversion]
does anyone know how to compare with the less than operator using chrono?
int time = atoi(argv[1]);
What units is time? seconds? nanoseconds? For this answer I'll assume seconds, but change it to whatever you need:
std::chrono::seconds time{atoi(arv[1])};
Next:
auto start = std::chrono::high_resolution_clock::now();
high_resolution_clock is going to be a type alias to either system_clock or steady_clock. The top of this answer explains the difference. I recommend chosing system_clock or steady_clock, depending on your needs, rather than letting the vendor choose for you.
while((std::chrono::duration_cast<chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start).count()) < time){
/*perform operation*/
}
Always try to stay within the chrono type system, instead of exiting it using .count(). Once you exit the chrono library, it can no longer help you. In this case it means doing the comparison using chrono units instead of ints.
When comparing chrono units, one does not need to cast such that both sides of the comparison are the same units. It is ok to compare seconds and milliseconds for example. chrono will do the comparison correctly, taking into account the different units.
I like to issue a function-scope using namespace std::chrono as I find repeated std::chrono:: overly verbose, making the code harder to read.
using namespace std::chrono;
seconds time{atoi(arv[1])};
auto start = steady_clock::now();
while(steady_clock::now() - start < time)
{
// perform operation
}
Or you can algebraically rearrange this:
while(steady_clock::now() < start + time)
{
// perform operation
}
Noticing the "constant" on the rhs, you can collect and rename that:
auto finish = steady_clock::now() + seconds{atoi(arv[1])};
while(steady_clock::now() < finish)
{
// perform operation
}
All of the above are equivalent, so you can choose whichever one you find more readable.
The error is in the precedence, you cast is performed after count() function, this cause that the cast is over a double value.
The problem can be solved in this way:
int time = atoi(argv[1]);
auto start = std::chrono::high_resolution_clock::now();
while(((std::chrono::duration_cast<chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start)).count()) < time){
/*perform operation*/
}

How To Return Elapsed Time From steady_clock as a Primitive Data Type (double)

First and foremost, let me say that I just starting using this library yesterday, so my understanding of it is still fairly basic. I'm trying to capture the FPS of a vision processing program I'm creating and output it to a screen using the chrono library. In my case, I need to cast the elapsed time taken after I start a steady_clock to a double (or some other numerical typedef I could treat like a double). I looked through reference documentation and tried working with the duration_cast and time_point_cast functions, but neither of those seem to be what I'm looking for.
My question is; is there any way to simply cast the numerical value of a clock's current state in seconds to a primitive data type?
Any help would be appreciated.
Like this:
#include <chrono>
#include <iostream>
#include <thread>
int main()
{
using namespace std::literals;
// measure time now
auto start = std::chrono::system_clock::now();
// wait some time
std::this_thread::sleep_for(1s);
// measure time again
auto end = std::chrono::system_clock::now();
// define a double-precision representation of seconds
using fsecs = std::chrono::duration<double, std::chrono::seconds::period>;
// convert from clock's duration type
auto as_fseconds = std::chrono::duration_cast<fsecs>(end - start);
// display as decimal seconds
std::cout << "duration was " << as_fseconds.count() << "s\n";
}
example output:
duration was 1.00006s
You could do it using the duration::count function.
For example you could get the duration in the number of milliseconds, and then divide the count by 1000.0 to get the number of seconds as a double.

using std::chrono::high_resolution_clock to write a frame 30 times per second

I'm using OpenCV to write a video file. For cv::VideoWriter to work correctly the call to the write() function has to happen exactly 30 times per second (for a 30fps video).
I found this code which uses the boost library to achieve this. I want to to the same but using std::chrono in my program. This is my implementation:
std::chrono::high_resolution_clock::time_point prev = std::chrono::high_resolution_clock::now();
std::chrono::high_resolution_clock::time_point current = prev;
long long difference = std::chrono::duration_cast<std::chrono::microseconds>(current-prev).count();
while(recording){
while (difference < 1000000/30){
current = std::chrono::high_resolution_clock::now();
difference = std::chrono::duration_cast<std::chrono::microseconds>(current-prev).count();
}
theVideoWriter.write(frameToRecord);
prev = prev + std::chrono::high_resolution_clock::duration(1000000000/30);
difference = std::chrono::duration_cast<std::chrono::microseconds>(current-prev).count();
}
theVideoWriter.release();
I'm not sure if thats the correct way to do this or if there is a more efficient way. Is there anything better than casting the duration to long long difference?
There is a basic tenant to working with chrono, which goes something like:
If you use count(), and/or you have conversion factors in your
chrono code, then you're trying too hard.
This is not your fault. There really is no good chrono tutorial and that is my bad, and I've recently decided I need to do something about that.
In your case, I recommend rewriting your code along the lines of the following:
First create a duration unit which represents the period of your frame rate:
using frame_period = std::chrono::duration<long long, std::ratio<1, 30>>;
Now when you say frame_period{1}, that means exactly 1/30 of a second.
The next thing to note is that chrono comparisons are always exact, as long as you stay in the chrono system. count() is a "trap door" for escaping out of the chrono system. Only escape out when you have no other choice. So...
auto prev = std::chrono::high_resolution_clock::now();
auto current = pref;
// Just get the difference, and don't worry about the units for now
auto difference = current-prev;
while(recording)
{
// Find out if the difference is less than one frame period
// This comparison will do all the conversions for you to get an exact answer
while (difference < frame_period{1})
{
current = std::chrono::high_resolution_clock::now();
// stay in "native units"...
difference = current-prev;
}
theVideoWriter.write(frameToRecord);
// This is a little tricky...
// prev + frame_period{1} creates a time_point with a complicated unit
// Use time_point_cast to convert (via truncation towards zero) back to
// the "native" duration of high_resolution_clock
using hr_duration = std::chrono::high_resolution_clock::duration;
prev = std::chrono::time_point_cast<hr_duration>(prev + frame_period{1});
// stay in "native units"...
difference = current-prev;
}
theVideoWriter.release();
The comments above are overly verbose once you get chrono. There's more comment than code above. But the above just works as you intended, with no need for "escaping out" of the chrono system.
Update
If you would want to initialize difference such that the inner loop won't be executed the first time, you could initialize it to something just over frame_period{1} instead of to 0. To do this, the utilities found here come in handy. Specifically ceil:
// round up
template <class To, class Rep, class Period>
To
ceil(const std::chrono::duration<Rep, Period>& d)
{
To t = std::chrono::duration_cast<To>(d);
if (t < d)
++t;
return t;
}
ceil is a replacement for duration_cast that will round up when the conversion is inexact, as opposed to truncate towards zero. Now you can say:
auto difference = ceil<hr_duration>(frame_period{1});
And you are guaranteed that difference >= frame_period{1}. Furthermore, it is known in practice that the duration of high_resolution_clock is nanoseconds, thus you can deduce (or test) that difference is actually initialized to 33,333,334ns, which is 2/3 of a nanosecond greater than 1/30 of a second, which equals frame_period{1}, which equals 33,333,333+1/3ns.

Estimating time left in C++11

I'm writing a progress bar class that outputs an updated progress bar every n ticks to an std::ostream:
class progress_bar
{
public:
progress_bar(uint64_t ticks)
: _total_ticks(ticks), ticks_occured(0),
_begin(std::chrono::steady_clock::now())
...
void tick()
{
// test to see if enough progress has elapsed
// to warrant updating the progress bar
// that way we aren't wasting resources printing
// something that hasn't changed
if (/* should we update */)
{
...
}
}
private:
std::uint64_t _total_ticks;
std::uint64_t _ticks_occurred;
std::chrono::steady_clock::time_point _begin;
...
}
I would like to also output the time remaining. I found a formula on another question that states time remaining is (variable names changed to fit my class):
time_left = (time_taken / _total_ticks) * (_total_ticks - _ticks_occured)
The parts I would like to fill in for my class are the time_left and the time_taken, using C++11's new <chrono> header.
I know I need to use a std::chrono::steady_clock, but I'm not sure how to integrate it into code. I assume the best way to measure the time would be a std::uint64_t as nanoseconds.
My questions are:
Is there a function in <chrono> that will convert the nanoseconds into an std::string, say something like "3m12s"?
Should I use the std::chrono::steady_clock::now() each time I update my progress bar, and subtract that from _begin to determine time_left?
Is there a better algorithm to determine time_left
Is there a function in that will convert the nanoseconds into
an std::string, say something like "3m12s"?
No. But I'll show you how you can easily do this below.
Should I use the std::chrono::steady_clock::now() each time I update
my progress bar, and subtract that from _begin to determine time_left?
Yes.
Is there a better algorithm to determine time_left
Yes. See below.
Edit
I had originally misinterpreted "ticks" as "clock ticks", when in actuality "ticks" has units of work and _ticks_occurred/_total_ticks can be interpreted as %job_done. So I've changed the proposed progress_bar below accordingly.
I believe the equation:
time_left = (time_taken / _total_ticks) * (_total_ticks - _ticks_occured)
is incorrect. It doesn't pass a sanity check: If _ticks_occured == 1 and _total_ticks is large, then time_left approximately equals (ok, slightly less) time_taken. That doesn't make sense.
I am rewriting the above equation to be:
time_left = time_taken * (1/percent_done - 1)
where
percent_done = _ticks_occurred/_total_ticks
Now as percent_done approaches zero, time_left approaches infinity, and when percent_done approaches 1, 'time_left approaches 0. When percent_done is 10%, time_left is 9*time_taken. This meets my expectations, assuming a roughly linear time cost per work-tick.
class progress_bar
{
public:
progress_bar(uint64_t ticks)
: _total_ticks(ticks), _ticks_occurred(0),
_begin(std::chrono::steady_clock::now())
// ...
{}
void tick()
{
using namespace std::chrono;
// test to see if enough progress has elapsed
// to warrant updating the progress bar
// that way we aren't wasting resources printing
// something that hasn't changed
if (/* should we update */)
{
// somehow _ticks_occurred is updated here and is not zero
duration time_taken = Clock::now() - _begin;
float percent_done = (float)_ticks_occurred/_total_ticks;
duration time_left = time_taken * static_cast<rep>(1/percent_done - 1);
minutes minutes_left = duration_cast<minutes>(time_left);
seconds seconds_left = duration_cast<seconds>(time_left - minutes_left);
}
}
private:
typedef std::chrono::steady_clock Clock;
typedef Clock::time_point time_point;
typedef Clock::duration duration;
typedef Clock::rep rep;
std::uint64_t _total_ticks;
std::uint64_t _ticks_occurred;
time_point _begin;
//...
};
Traffic in std::chrono::durations whenever you can. That way <chrono> does all the conversions for you. typedefs can ease the typing with the long names. And breaking down the time into minutes and seconds is as easy as shown above.
As bames53 notes in his answer, if you want to use my <chrono_io> facility, that's cool too. Your needs may be simple enough that you don't want to. It is a judgement call. bames53's answer is a good answer. I thought these extra details might be helpful too.
Edit
I accidentally left a bug in the code above. And instead of just patch the code above, I thought it would be a good idea to point out the bug and show how to use <chrono> to fix it.
The bug is here:
duration time_left = time_taken * static_cast<rep>(1/percent_done - 1);
and here:
typedef Clock::duration duration;
In practice steady_clock::duration is usually based on an integral type. <chrono> calls this the rep (short for representation). And when percent_done is greater than 50%, the factor being multiplied by time_taken is going to be less than 1. And when rep is integral, that gets cast to 0. So this progress_bar only behaves well during the first 50% and predicts 0 time left during the last 50%.
The key to fixing this is to traffic in durations that are based on floating point instead of integers. And <chrono> makes this very easy to do.
typedef std::chrono::steady_clock Clock;
typedef Clock::time_point time_point;
typedef Clock::period period;
typedef std::chrono::duration<float, period> duration;
duration now has the same tick period as steady_clock::duration but uses a float for the representation. And now the computation for time_left can leave off the static_cast:
duration time_left = time_taken * (1/percent_done - 1);
Here's the whole package again with these fixes:
class progress_bar
{
public:
progress_bar(uint64_t ticks)
: _total_ticks(ticks), _ticks_occurred(0),
_begin(std::chrono::steady_clock::now())
// ...
{}
void tick()
{
using namespace std::chrono;
// test to see if enough progress has elapsed
// to warrant updating the progress bar
// that way we aren't wasting resources printing
// something that hasn't changed
if (/* should we update */)
{
// somehow _ticks_occurred is updated here and is not zero
duration time_taken = Clock::now() - _begin;
float percent_done = (float)_ticks_occurred/_total_ticks;
duration time_left = time_taken * (1/percent_done - 1);
minutes minutes_left = duration_cast<minutes>(time_left);
seconds seconds_left = duration_cast<seconds>(time_left - minutes_left);
std::cout << minutes_left.count() << "m " << seconds_left.count() << "s\n";
}
}
private:
typedef std::chrono::steady_clock Clock;
typedef Clock::time_point time_point;
typedef Clock::period period;
typedef std::chrono::duration<float, period> duration;
std::uint64_t _total_ticks;
std::uint64_t _ticks_occurred;
time_point _begin;
//...
};
Nothing like a little testing... ;-)
The chrono library includes types for representing durations. You shouldn't convert that to a flat integer of some 'known' unit. When you want a known unit just use the chrono types, e.g. 'std::chrono::nanoseconds', and duration_cast. Or create your own duration type using a floating point representation and one of the SI ratios. E.g. std::chrono::duration<double,std::nano>. Without duration_cast or a floating point duration rounding is prohibited at compile time.
The IO facilities for chrono didn't make it into C++11, but you can get source from here. Using this you can just ignore the duration type, and it will print the right units. I don't think there's anything there to that will show the time in minutes, seconds, etc., but such a thing shouldn't be too hard to write.
I don't know that there's too much reason to be concerned about calling steady_clock::now() frequently, if that's what your asking. I'd expect most platforms to have a pretty fast timer for just that sort of thing. It does depend on the implementation though. Obviously it's causing an issue for you, so maybe you could only call steady_clock::now() inside the if (/* should we update */) block, which should put a reasonable limit on the call frequency.
Obviously there are other ways to estimate the time remaining. For example instead of taking the average over the progress so far (which is what the formula you show does), you could take the average from the last N ticks. Or do both and take a weighted average of the two estimates.