2

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?

DeepDeadpool
  • 1,441
  • 12
  • 36
  • I think it returns the number of seconds since Jan 1, 1970. – SunsetQuest Jul 04 '15 at 02:16
  • For sub-second timing on POSIX systems, consider [`clock_gettime()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_gettime.html) (nanosecond resolution, modern, preferred) or [`gettimeofday()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/gettimeofday.html) (microsecond resolution, less modern, strictly deprecated, but available on Mac OS X where `clock_gettime()` is not). There used to be [`ftime()`](http://pubs.opengroup.org/onlinepubs/009695399/functions/ftime.html) (millisecond resolution, ancient, deprecated) too — that's from the POSIX 2001 (2004) manual. – Jonathan Leffler Jul 04 '15 at 02:42

3 Answers3

4

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;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
SunsetQuest
  • 8,041
  • 2
  • 47
  • 42
  • [time](http://www.cplusplus.com/reference/ctime/time/) and [clock](http://www.cplusplus.com/reference/ctime/clock/) – Rodolfo Jul 04 '15 at 02:24
1

This has nothing to do with time() or difftime(). It is purely cout in c++.

See here: How do I print a double value with full precision using cout?

Community
  • 1
  • 1
user1602017
  • 1,109
  • 8
  • 8
-1
int main()
{
    time_t o_test, f_test;
    time(&o_test);
    while (1)
    {
        time(&f_test);
        std::cout << difftime(f_test, o_test) << std::endl;
    }
}
jdl
  • 6,151
  • 19
  • 83
  • 132
  • 1
    You've not explained what you've changed or why. The `time()` function takes a pointer to `time_t` argument and will write the value it returns in the variable pointed at if the pointer is not null. The original code is perfectly correct. Your revision is also OK. (Personally, I very seldom use `time(&var)` and almost always use `time(0)` or `time(NULL)` instead). But you've done nothing about explaining why the output from `difftime()` is always an integral value. – Jonathan Leffler Jul 04 '15 at 02:46