better precision from ctime? (was Re: Get rid of a (float) cast in timer class)

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.
 
V

Victor Bazarov

Nicolas said:
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.

That's on _your_ system. On a different system it _can_ be different.
Nowhere in the Standard does it say that 'time()' has anything to do with
seconds.
I can use clock() to get a precise usage
of cpu time (at least 4 decimals).

On _your_ system.
I would still like to have a total
elapsed time in that same precision.

It may be possible on _your_ system. You need to ask about platform-
specific time functions in the newsgroup dedicated to your platform.
For now, I would still rather
not use external libraries such as boost if possible.

'Boost' is non-standard. Standard 'time' does not promise any precision.
It's all implementation-defined. If your implementation's 'time' is not
precise enough, use OS-specific means.
[..]
Any suggestions to improve precision in the elapsed_time?

Use OS-specific means.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top