'Is there a function that can limit a program to run only under 2 minuets?
I am writing code that terminates by entering e or t , and I want everything to work under two minuets, but I cant get things to work once I include the delay or sleep, tried using the chrono lib
int main()
{
string ee;
int x=5, y=3;
while (true) {
std::cout <<y<< std::endl;
cout <<x<< std::endl;
cin >>ee;
if (ee =="e" { break;}
if (ee =="e" { break;}
if (ee =="E" { break;}
if (ee =="T" { break;}
}
}
Solution 1:[1]
The elaborate on my comment above:
There is no standard c++ function to limit the runtime of a program as such. You'll need to implement such a mechanism, according to your specific needs.
My solution below assumes that you do not intend to abort the std::cin
operation (cin >>ee;
). I assumed that the usage of std::cin
was just to simulate some way of breaking a long iterative process.
If this is the case, you can do get a time measurement before the long process. Then in each iteration get a new time measurement and exit it if your maximum time elapsed.
Something like the following:
#include <string>
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
int x = 5, y = 3;
auto tStart = std::chrono::steady_clock::now();
while (true) {
auto tNow = std::chrono::steady_clock::now();
auto elapsedSecs = std::chrono::duration_cast<std::chrono::seconds>(tNow - tStart).count();
if (elapsedSecs >= 120)
{
// 2 minutes or more passed => exit
break;
}
// Simulate one iteration of the long process:
std::cout << y << std::endl;
std::cout << x << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
return 0;
}
Note: it's better to avoid using namespace std
- see here Why is "using namespace std;" considered bad practice?.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |