c++ run loop for 5 seconds
To run a loop in C++ for 5 seconds, you can make use of the <chrono>
and <thread>
libraries. Here's an example code snippet that demonstrates this:
#include <iostream>
#include <chrono>
#include <thread>
int main() {
// Get the current time
auto start = std::chrono::high_resolution_clock::now();
// Loop until 5 seconds have passed
while (true) {
// Get the current time
auto end = std::chrono::high_resolution_clock::now();
// Calculate the elapsed time in seconds
auto duration = std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
// Check if 5 seconds have passed
if (duration >= 5) {
break;
}
// Print a message every second
std::cout << "Looping..." << std::endl;
// Sleep for 1 second
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 0;
}
Explanation of each step:
#include <iostream>
: This line includes the input/output stream library, which allows us to usestd::cout
to print messages to the console.#include <chrono>
: This line includes the<chrono>
library, which provides functions for working with time.#include <thread>
: This line includes the<thread>
library, which provides functions for working with threads.auto start = std::chrono::high_resolution_clock::now();
: This line uses thestd::chrono::high_resolution_clock::now()
function to get the current time and assigns it to the variablestart
.while (true) { ... }
: This line starts an infinite loop that will continue until the condition is explicitly broken.auto end = std::chrono::high_resolution_clock::now();
: This line gets the current time and assigns it to the variableend
.auto duration = std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
: This line calculates the elapsed time in seconds by subtracting thestart
time from theend
time and then converting it to seconds usingstd::chrono::duration_cast
. The result is assigned to the variableduration
.if (duration >= 5) { break; }
: This line checks if 5 seconds have passed by comparing theduration
variable to 5. If 5 seconds have passed, the loop is exited using thebreak
statement.std::cout << "Looping..." << std::endl;
: This line prints the message "Looping..." to the console usingstd::cout
.std::this_thread::sleep_for(std::chrono::seconds(1));
: This line pauses the execution of the program for 1 second using thestd::this_thread::sleep_for
function from the<thread>
library.return 0;
: This line ends themain()
function and returns 0, indicating successful program execution.
By running this code, the loop will keep printing "Looping..." every second until 5 seconds have passed.