K
Kai-Uwe Bux
[code snipped]Joe said:For some reason, this still doesn't work. I think the problem is that
time() measures in seconds, yet my start_time + exec_time is adding
hundreds or thousands of milliseconds to seconds, so my now time will
never surpass end_time for a long time.
How should I go about fixing that. I would like the millisecond accuracy
between times.
I don't know about guaranteed accuracy. But you could use double and seconds
throughout:
#include <ctime>
#include <iostream>
#include <ostream>
#include <cstdlib>
double get_random ( double bound ) {
// WARNING: not uniform
return ( bound * ( std::rand() / (RAND_MAX+1.0) ) );
}
double const max_seconds = 4.0;
double seconds ( clock_t ticks ) {
return ( double( ticks ) / double( CLOCKS_PER_SEC ) );
}
double get_seconds ( void ) {
return ( seconds( clock() ) );
}
int main ( void ) {
std::srand( time(0) );
double start = get_seconds();
double random_time = get_random( max_seconds );
std::cout << start << '\n';
std::cout << random_time << '\n';
while ( get_seconds() - start < random_time ) {
}
std::cout << get_seconds() << '\n';
}
Best
Kai-Uwe Bux