秒表可暂停,重置C++
时间: 2023-07-11 09:20:40 浏览: 115
是的,C++语言可以实现一个带有暂停和重置功能的秒表。可以使用<chrono>头文件中的高精度计时器std::chrono::high_resolution_clock来实现。
下面是一个简单的实现示例:
```c++
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
class Stopwatch {
private:
chrono::time_point<chrono::high_resolution_clock> start_time;
chrono::duration<double> elapsed_time;
bool is_paused;
chrono::time_point<chrono::high_resolution_clock> pause_time;
public:
Stopwatch() : elapsed_time(0), is_paused(false) {}
void start() {
start_time = chrono::high_resolution_clock::now();
is_paused = false;
}
void pause() {
if (!is_paused) {
pause_time = chrono::high_resolution_clock::now();
elapsed_time += pause_time - start_time;
is_paused = true;
}
}
void resume() {
if (is_paused) {
start_time = chrono::high_resolution_clock::now();
is_paused = false;
}
}
void reset() {
elapsed_time = chrono::duration<double>(0);
is_paused = false;
}
double get_elapsed_time() {
if (!is_paused) {
elapsed_time = chrono::high_resolution_clock::now() - start_time;
}
return elapsed_time.count();
}
};
int main() {
Stopwatch stopwatch;
stopwatch.start();
for (int i = 0; i < 10; ++i) {
cout << "elapsed time: " << stopwatch.get_elapsed_time() << endl;
if (i == 5) {
stopwatch.pause();
cout << "pause for 3 seconds" << endl;
this_thread::sleep_for(chrono::seconds(3));
stopwatch.resume();
}
this_thread::sleep_for(chrono::seconds(1));
}
stopwatch.reset();
cout << "reset stopwatch" << endl;
cout << "elapsed time: " << stopwatch.get_elapsed_time() << endl;
return 0;
}
```
这个示例实现了一个带有暂停和重置功能的秒表,使用了计时器和线程库。其中,start()方法开始计时,pause()方法暂停计时,resume()方法恢复计时,reset()方法重置计时器,get_elapsed_time()方法获取经过的时间。在main()函数中,我们进行了一些简单的测试,模拟了一个计时时间为10秒,其中第5秒到第8秒暂停了3秒的过程。
阅读全文