PDA

View Full Version : measuring time


tricolaire
12-17-2006, 07:43 PM
as far as measuring the passage of time goes in c++, I know only of the function contained in ctime.h, time()

is there a way in c++ to measure time in something smaller than seconds?

TIA

oracleguy
12-17-2006, 09:04 PM
Yeah there is:


clock_t start, end;
double time;

start = clock();
... do something ...
end = clock();

time = (double(end) - double(start)) / CLOCKS_PER_SEC;


You can measure fractions of a second using this method. You'll need to include ctime and time.h I believe.

tricolaire
12-17-2006, 10:04 PM
where is CLOCKS_PER_SEC defined?

oracleguy
12-17-2006, 11:25 PM
In time.h

rpgfan3233
12-18-2006, 02:01 AM
/* This defines CLOCKS_PER_SEC, which is the number of processor clock
ticks per second. */
# include <bits/time.h>

/* This is the obsolete POSIX.1-1988 name for the same constant. */
# if !defined __STRICT_ANSI__ && !defined __USE_XOPEN2K
# ifndef CLK_TCK
# define CLK_TCK CLOCKS_PER_SEC
# endif
# endif

Note that it mentioned <bits/time.h> for CLOCKS_PER_SEC, so we look in there:
/* ISO/IEC 9899:1990 7.12.1: <time.h>
The macro `CLOCKS_PER_SEC' is the number per second of the value
returned by the `clock' function. */
/* CAE XSH, Issue 4, Version 2: <time.h>
The value of CLOCKS_PER_SEC is required to be 1 million on all
XSI-conformant systems. */
# define CLOCKS_PER_SEC 1000000l

# if !defined __STRICT_ANSI__ && !defined __USE_XOPEN2K
/* Even though CLOCKS_PER_SEC has such a strange value CLK_TCK
presents the real value for clock ticks per second for the system. */
# include <bits/types.h>
extern long int __sysconf (int);
# define CLK_TCK ((__clock_t) __sysconf (2)) /* 2 is _SC_CLK_TCK */
# endif

/* #### SKIPPING SOME OF THE HEADER FILE #### */

/* A time value that is accurate to the nearest
microsecond but also has a range of years. */
struct timeval
{
__time_t tv_sec; /* Seconds. */
__suseconds_t tv_usec; /* Microseconds. */
};
# endif /* struct timeval */
#endif /* need timeval */

In short, you may need to do a couple of tests with CLOCKS_PER_SEC, CLK_TCK and the timeval struct directly above to see what gives you the value you want. Also note that if CLK_TCK is not defined in <bits/time.h> (usually because it isn't found), CLK_TCK is defined as CLOCKS_PER_SEC in <time.h> (<ctime>).

That information was for gcc 4.1.1 on Fedora Core 6, but it should work for you.