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 int
s.
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.