1
#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.

heyblackduck
  • 117
  • 13
  • You [really don't](http://stackoverflow.com/a/10902614/1621391) need [*elaborated type-specifiers*](http://en.cppreference.com/w/cpp/language/elaborated_type_specifier) in C++... It just makes the code messy – WhiZTiM Jan 26 '17 at 19:34
  • Perhaps a Unix tag should be added, since these are not standard c++ functions and structures. – François Andrieux Jan 26 '17 at 19:39
  • @FrançoisAndrieux which is interesting since you can do this with standard C++ – Mgetz Jan 26 '17 at 19:42
  • @Mgetz This is for learning purposes since I want to learn how to use gettimeofday, I know there are better ways to do this such as using POSIX clock. – heyblackduck Jan 26 '17 at 19:44
  • 1
    @RobertMedina I was actually thinking of [`std::chrono::system_clock`](http://en.cppreference.com/w/cpp/chrono/system_clock) – Mgetz Jan 26 '17 at 19:48
  • 4
    Without the extra print statement your delta time is most likely 0, causing the print statement to always execute because 0 += 0, means everyMinute is always 0. That's my guess anyway. – Borgleader Jan 26 '17 at 19:51

0 Answers0