C++ 中的秒表 class
Stopwatch class in c++
我必须用 C++ 编写秒表 class。我尝试这样做的方法是定义一个变量来保存圈数(名为 'time')和一个 bool
,我用它来查看手表是启动还是停止。输入 char
时,计时器应启动并设置 time1
。当输入另一个字符时,bool
切换到 false
并设置 time2
,然后打印 time2-time1
。这应该是可重复的,直到输入 'n'
我也不太确定我理解 time_t 的时间单位是什么。在我的代码中,每次我尝试测量时间间隔时,我得到的 return 值为 ±40 个单位一圈,我猜这是程序的运行时间,而不是真正的间隔时间。
#ifndef stoppuhr_hpp
#define stoppuhr_hpp
#include <iostream>
#include <time.h>
class Stoppuhr{
private:
bool running;
clock_t time;
public:
void pushButtonStartStop () {
char t=0;
running=false;
time=0;
std::cout << "to start/stop watch please press a key, to end
clock type 'n' " << std::endl;
clock_t time1=0;
clock_t time2=0;
std::cout << time;
while (t!='n') {
std::cin >> t;
running= !running;
if (running) {
time1=clock();
}
else {
time2=clock();
time+=time2-time1;
std::cout << time << std::endl;
}
}
}
};
#endif /* stoppuhr_hpp */
I also am not quite sure I understand what unit of time time_t is in.
time_t
表示的时间单位是指定的实现。通常,它表示秒,由 POSIX.
指定
但是,您没有在程序的任何地方使用 time_t
。
I am guessing is the runtime of the program
我建议不要猜测,而是阅读文档。 clock()
returns 自某个时间点以来程序使用的处理器时间。因此,减去 clock()
返回的两个时间点将为您提供这些时间点之间使用的处理器时间。 clock_t
的单位是1 / CLOCKS_PER_SEC
秒。
i get a return value of ±40 units every time
clock
的粒度是指定的实现。您的系统上可能有 40 个单位。该程序在等待输入时几乎不消耗任何处理器时间。
I have to write a stopwatch class
秒表通常测量真实世界时间,即挂钟时间。测量处理器时间对于这项任务是徒劳的。
我建议改用 std::chrono::steady_clock::now
。
如果你坚持使用time.h,那么你可以使用time(nullptr)
来获取挂钟时间,但我不推荐它。
我必须用 C++ 编写秒表 class。我尝试这样做的方法是定义一个变量来保存圈数(名为 'time')和一个 bool
,我用它来查看手表是启动还是停止。输入 char
时,计时器应启动并设置 time1
。当输入另一个字符时,bool
切换到 false
并设置 time2
,然后打印 time2-time1
。这应该是可重复的,直到输入 'n'
我也不太确定我理解 time_t 的时间单位是什么。在我的代码中,每次我尝试测量时间间隔时,我得到的 return 值为 ±40 个单位一圈,我猜这是程序的运行时间,而不是真正的间隔时间。
#ifndef stoppuhr_hpp
#define stoppuhr_hpp
#include <iostream>
#include <time.h>
class Stoppuhr{
private:
bool running;
clock_t time;
public:
void pushButtonStartStop () {
char t=0;
running=false;
time=0;
std::cout << "to start/stop watch please press a key, to end
clock type 'n' " << std::endl;
clock_t time1=0;
clock_t time2=0;
std::cout << time;
while (t!='n') {
std::cin >> t;
running= !running;
if (running) {
time1=clock();
}
else {
time2=clock();
time+=time2-time1;
std::cout << time << std::endl;
}
}
}
};
#endif /* stoppuhr_hpp */
I also am not quite sure I understand what unit of time time_t is in.
time_t
表示的时间单位是指定的实现。通常,它表示秒,由 POSIX.
但是,您没有在程序的任何地方使用 time_t
。
I am guessing is the runtime of the program
我建议不要猜测,而是阅读文档。 clock()
returns 自某个时间点以来程序使用的处理器时间。因此,减去 clock()
返回的两个时间点将为您提供这些时间点之间使用的处理器时间。 clock_t
的单位是1 / CLOCKS_PER_SEC
秒。
i get a return value of ±40 units every time
clock
的粒度是指定的实现。您的系统上可能有 40 个单位。该程序在等待输入时几乎不消耗任何处理器时间。
I have to write a stopwatch class
秒表通常测量真实世界时间,即挂钟时间。测量处理器时间对于这项任务是徒劳的。
我建议改用 std::chrono::steady_clock::now
。
如果你坚持使用time.h,那么你可以使用time(nullptr)
来获取挂钟时间,但我不推荐它。