Classes, Objects, and Methods
in C++
#include <cstdio>
#include <ctime>
#include <unistd.h>
class StopWatch
{
public:
StopWatch();
void start();
void stop();
void reset();
double get_elapsed_time();
bool is_running();
private:
double elapsed_time;
bool running;
time_t start_time;
};
StopWatch::StopWatch()
{
running = false;
elapsed_time = 0;
}
void
StopWatch::reset()
{
running = false;
elapsed_time = 0;
}
bool
StopWatch::is_running()
{
return running;
}
void
StopWatch::start()
{
if (running) {
return;
}
start_time = time(NULL);
running = true;
}
void
StopWatch::stop()
{
if (! running) {
return;
}
time_t current_time = time(NULL);
running = false;
elapsed_time += difftime(current_time, start_time);
}
double
StopWatch::get_elapsed_time()
{
double elapsed = elapsed_time;
if (running) {
time_t current_time = time(NULL);
elapsed += difftime(current_time, start_time);
}
return elapsed;
}
int
main()
{
StopWatch watch;
watch.start();
for (int i = 0; i < 5; ++i) {
sleep(1);
printf("Elapsed time: %f\n", watch.get_elapsed_time());
}
watch.stop();
sleep(5);
printf("Elapsed time: %f\n", watch.get_elapsed_time());
return 0;
}