Reputation: 117
#include <iostream>
#include <sys/time.h>
static long elapsedTime(struct timeval &then)
{
struct timeval when;
gettimeofday(&when, NULL);
long result = (when.tv_sec - then.tv_sec) * 1000;
result += (when.tv_usec - then.tv_usec) / 1000;
then = when;
return (result > 0) ? result : 0;
}
int main()
{
struct timeval now;
gettimeofday(&now, NULL);
long elapsed, everyMinute = 0;
while (true) {
elapsed = elapsedTime(now);
everyMinute += elapsed;
if (everyMinute % 1000 == 0)
std::cout << "After: " << everyMinute << std::endl;
}
return 0;
}
I am trying to get this loop to print every minute but gettimeofday
gives me unexpected behavior. For example this line std::cout << "Before: " << everyMinute << std::endl;
will cause the if to work but without it I just get zeros: here is snippet but it is better to plug into your own compiler.
Upvotes: 1
Views: 875