I need to implement a function that should do specified task for specified duration which is passed to it as parameter (std::chrono::milliseconds).
I have come up with code :
void Run(std::chrono::milliseconds ms)
{
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
while (elapsed_seconds <= (ms / 1000))
{
std::cout << "Running" << std::endl;
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
}
}
int main()
{
{
std::chrono::milliseconds ms(30000);
Run(ms);
system("Pause");
}
I suppose the code to print Running for 30 seconds and then exit. But it does not do so. How do I achieve such behavior with C++ <chrono>
All you really need is to know the end point and then loop until that point is reached:
#include <chrono>
void Run(std::chrono::milliseconds ms)
{
std::chrono::time_point<std::chrono::system_clock> end;
end = std::chrono::system_clock::now() + ms; // this is the end point
while(std::chrono::system_clock::now() < end) // still less than the end?
{
std::cout << "Running" << std::endl;
}
}
int main()
{
std::chrono::milliseconds ms(3000);
Run(ms);
system("Pause");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With