Search code examples
c++timedifftime

Why is difftime Only Returning Whole Numbers?


For some reason difftime is only returning whole numbers. My code is pretty simple.

#include <time.h>

int main()
{
    time_t test = time(NULL);
    while (1)
    {
        std::cout << difftime(time(NULL), test) << std::endl;
    }
}

My output looks like

0...
1...
2...
3...

Isn't difftime supposed to return doubles?


Solution

  • The function time() returns to the nearest second and difftime() just returns the difference of those. Any whole number minus a whole number is a whole number basically (but it is returned as a double).

    By the way, for a more accurate timer:

    time_t test = clock();
    while (1)
    {
        std::cout << float(clock() - test) / CLOCKS_PER_SEC << std::endl;
    }