N
Nicolas Blais
Hi again,
I modified my timer class to be more portable (I used to have #include
<sys/time.h>. As I mentionned in an other post, with <ctime> I can't seem
to get double precision since according to 'man 3 time', time() is precise
to the second. I can use clock() to get a precise usage of cpu time (at
least 4 decimals). I would still like to have a total elapsed time in that
same precision. For now, I would still rather not use external libraries
such as boost if possible.
Here's the class:
#include <ctime>
class chrono {
public:
chrono() : running(false), start_clock(0), start_time(0), acc_time(0) { }
~chrono() {};
void start();
void restart();
void stop();
double check();
private:
bool running;
clock_t start_clock;
time_t start_time;
double acc_time;
double elapsed_time();
};
void chrono::start() {
if (running) return;
running = true;
start_clock = clock();
start_time = time(0);
}
double chrono::elapsed_time() {
time_t acc_sec = time(0) - start_time; // Precise only to the second...
// The following block returns cpu time used
//if (acc_sec < 3600)
// return (clock() - start_clock) / (1.0 * CLOCKS_PER_SEC);
//else
return acc_sec;
}
void chrono::stop() {
if (running) acc_time += elapsed_time();
running = false;
}
double chrono::check() {
return (acc_time + (running ? elapsed_time() : 0));
}
Any suggestions to improve precision in the elapsed_time?
Nicolas.
I modified my timer class to be more portable (I used to have #include
<sys/time.h>. As I mentionned in an other post, with <ctime> I can't seem
to get double precision since according to 'man 3 time', time() is precise
to the second. I can use clock() to get a precise usage of cpu time (at
least 4 decimals). I would still like to have a total elapsed time in that
same precision. For now, I would still rather not use external libraries
such as boost if possible.
Here's the class:
#include <ctime>
class chrono {
public:
chrono() : running(false), start_clock(0), start_time(0), acc_time(0) { }
~chrono() {};
void start();
void restart();
void stop();
double check();
private:
bool running;
clock_t start_clock;
time_t start_time;
double acc_time;
double elapsed_time();
};
void chrono::start() {
if (running) return;
running = true;
start_clock = clock();
start_time = time(0);
}
double chrono::elapsed_time() {
time_t acc_sec = time(0) - start_time; // Precise only to the second...
// The following block returns cpu time used
//if (acc_sec < 3600)
// return (clock() - start_clock) / (1.0 * CLOCKS_PER_SEC);
//else
return acc_sec;
}
void chrono::stop() {
if (running) acc_time += elapsed_time();
running = false;
}
double chrono::check() {
return (acc_time + (running ? elapsed_time() : 0));
}
Any suggestions to improve precision in the elapsed_time?
Nicolas.