Copyright 1999-2004, 2010-2012 Free Software Foundation, Inc.
This file is part of the GNU MP Library.
The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of either:
* the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
or
* the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
or both in parallel, as here.
The GNU MP Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with the GNU MP Library. If not,
see https://www.gnu.org/licenses/. */
/* Usage:
The code in this file implements the lowest level of time measuring, simple one-time measuring of time between two points.
void speed_starttime (void) double speed_endtime (void) Call speed_starttime to start measuring, and then call speed_endtime when done.
speed_endtime returns the time taken, in seconds. Or if the timebase is in CPU cycles and the CPU frequency is unknown then speed_endtime returns cycles. Applications can identify the cycles return by checking for speed_cycletime (described below) equal to 1.0.
If some sort of temporary glitch occurs then speed_endtime returns 0.0. Currently this is for various cases where a negative time has occurred. This unfortunately occurs with getrusage on some systems, and with the hppa cycle counter on hpux.
double speed_cycletime The time in seconds for each CPU cycle. For example on a 100 MHz CPU this would be 1.0e-8.
If the CPU frequency is unknown, then speed_cycletime is either 0.0 or 1.0. It's 0.0 when speed_endtime is returning seconds, or it's 1.0 when speed_endtime is returning cycles.
It may be noted that "speed_endtime() / speed_cycletime" gives a measured time in cycles, irrespective of whether speed_endtime is returning cycles or seconds. (Assuming cycles can be had, ie. it's either cycles already or the cpu frequency is known. See also speed_cycletime_need_cycles below.)
double speed_unittime The unit of time measurement accuracy for the timing method in use. This is in seconds or cycles, as per speed_endtime.
char speed_time_string[] A null-terminated string describing the time method in use.
void speed_time_init (void) Initialize time measuring. speed_starttime() does this automatically, so it's only needed if an application wants to inspect the above global variables before making a measurement.
int speed_precision The intended accuracy of time measurements. speed_measure() in common.c for instance runs target routines with enough repetitions so it takes at least "speed_unittime * speed_precision" (this expression works for both cycles or seconds from speed_endtime).
A program can provide an option so the user to set speed_precision. If speed_precision is zero when speed_time_init or speed_starttime first run then it gets a default based on the measuring method chosen. (More precision for higher accuracy methods.)
void speed_cycletime_need_seconds (void) Call this to demand that speed_endtime will return seconds, and not cycles. If only cycles are available then an error is printed and the program exits.
void speed_cycletime_need_cycles (void) Call this to demand that speed_cycletime is non-zero, so that "speed_endtime() / speed_cycletime" will give times in cycles.
Notes:
Various combinations of cycle counter, read_real_time(), getrusage(), gettimeofday() and times() can arise, according to which are available and their precision.
Allowing speed_endtime() to return either seconds or cycles is only a slight complication and makes it possible for the speed program to do some sensible things without demanding the CPU frequency. If seconds are being measured then it can always print seconds, and if cycles are being measured then it can always print them without needing to know how long they are. Also the tune program doesn't care at all what the units are.
GMP_CPU_FREQUENCY can always be set when the automated methods in freq.c fail. This will be needed if times in seconds are wanted but a cycle counter is being used, or if times in cycles are wanted but getrusage or another seconds based timer is in use.
If the measuring method uses a cycle counter but supplements it with getrusage or the like, then knowing the CPU frequency is mandatory since the code compares values from the two.
Not done:
Solaris gethrtime() seems no more than a slow way to access the Sparc V9 cycle counter. gethrvtime() seems to be relevant only to light weight processes, it doesn't for instance give nanosecond virtual time. So neither of these are used.
Bugs:
getrusage_microseconds_p is fundamentally flawed, getrusage and gettimeofday can have resolutions other than clock ticks or microseconds, for instance IRIX 5 has a tick of 10 ms but a getrusage of 1 ms.
Enhancements:
The SGI hardware counter has 64 bits on some machines, which could be used when available. But perhaps 32 bits is enough range, and then rely on the getrusage supplement.
Maybe getrusage (or times) should be used as a supplement for any wall-clock measuring method. Currently a wall clock with a good range (eg. a 64-bit cycle counter) is used without a supplement.
On PowerPC the timebase registers could be used, but would have to do something to find out the speed. On 6xx chips it's normally 1/4 bus speed, on 4xx chips it's either that or an external clock. Measuring
against gettimeofday might be ok. */
#if HAVE_FCNTL_H #include <fcntl.h> /* for open() */ #endif
#if HAVE_STDINT_H #include <stdint.h> /* for uint64_t */ #endif
#if HAVE_UNISTD_H #include <unistd.h> /* for sysconf() */ #endif
#include <sys/types.h>
#if TIME_WITH_SYS_TIME # include <sys/time.h> /* for struct timeval */ # include <time.h> #else # if HAVE_SYS_TIME_H # include <sys/time.h> # else # include <time.h> # endif #endif
#if HAVE_SYS_MMAN_H #include <sys/mman.h> /* for mmap() */ #endif
#if HAVE_SYS_RESOURCE_H #include <sys/resource.h> /* for struct rusage */ #endif
#if HAVE_SYS_SYSSGI_H #include <sys/syssgi.h> /* for syssgi() */ #endif
#if HAVE_SYS_SYSTEMCFG_H #include <sys/systemcfg.h> /* for RTC_POWER on AIX */ #endif
#if HAVE_SYS_TIMES_H #include <sys/times.h> /* for times() and struct tms */ #endif
#include"gmp-impl.h"
#include"speed.h"
/* strerror is only used for some stuff on newish systems, no need to have a
proper replacement */ #if ! HAVE_STRERROR #define strerror(n) "" #endif
/* Conditionals for the time functions available are done with normal C code, which is a lot easier than wildly nested preprocessor directives.
The choice of what to use is partly made at run-time, according to whether the cycle counter works and the measured accuracy of getrusage and gettimeofday.
A routine that's not available won't be getting called, but is an abort() to be sure it isn't called mistakenly.
It can be assumed that if a function exists then its data type will, but if the function doesn't then the data type might or might not exist, so the type can't be used unconditionally. The "struct_rusage" etc macros
provide dummies when the respective function doesn't exist. */
/* for RTC_POWER format, ie. seconds and nanoseconds */ #define TIMEBASESTRUCT_SECS(t) ((t)->tb_high + (t)->tb_low * 1e-9)
/* Return a string representing a time in seconds, nicely formatted.
Eg. "10.25ms". */ char *
unittime_string (double t)
{ staticchar buf[128];
constchar *unit; int prec;
/* choose units and scale */ if (t < 1e-6)
t *= 1e9, unit = "ns"; elseif (t < 1e-3)
t *= 1e6, unit = "us"; elseif (t < 1.0)
t *= 1e3, unit = "ms"; else
unit = "s";
int
cycles_works_p (void)
{ staticint result = -1;
if (result != -1) goto done;
/* FIXME: On linux, the cycle counter is not saved and restored over * context switches, making it almost useless for precise cputime * measurements. When available, it's better to use clock_gettime, * which seems to have reasonable accuracy (tested on x86_32, * linux-2.6.26, glibc-2.7). However, there are also some linux * systems where clock_gettime is broken in one way or the other, * like CLOCK_PROCESS_CPUTIME_ID not implemented (easy case) or * kind-of implemented but broken (needs code to detect that), and * on those systems a wall-clock cycle counter is the least bad * fallback. * * So we need some code to disable the cycle counter on some but not
* all linux systems. */ #ifdef SIGILL
{
RETSIGTYPE (*old_handler) (int); unsigned cycles[2];
old_handler = signal (SIGILL, cycles_works_handler); if (old_handler == SIG_ERR)
{ if (speed_option_verbose)
printf ("cycles_works_p(): SIGILL not supported, assuming speed_cyclecounter() works\n"); goto yes;
} if (setjmp (cycles_works_buf))
{ if (speed_option_verbose)
printf ("cycles_works_p(): SIGILL during speed_cyclecounter(), so doesn't work\n");
result = 0; goto done;
}
speed_cyclecounter (cycles);
signal (SIGILL, old_handler); if (speed_option_verbose)
printf ("cycles_works_p(): speed_cyclecounter() works\n");
} #else
if (speed_option_verbose)
printf ("cycles_works_p(): SIGILL not defined, assuming speed_cyclecounter() works\n"); goto yes; #endif
yes:
result = 1;
done: return result;
}
/* The number of clock ticks per second, but looking at sysconf rather than
just CLK_TCK, where possible. */ long
clk_tck (void)
{ staticlong result = -1L; if (result != -1L) return result;
#if HAVE_SYSCONF
result = sysconf (_SC_CLK_TCK); if (result != -1L)
{ if (speed_option_verbose)
printf ("sysconf(_SC_CLK_TCK) is %ld per second\n", result); return result;
}
fprintf (stderr, "sysconf(_SC_CLK_TCK) not working, using CLK_TCK instead\n"); #endif
#ifdef CLK_TCK
result = CLK_TCK; if (speed_option_verbose)
printf ("CLK_TCK is %ld per second\n", result); return result; #else
fprintf (stderr, "CLK_TCK not defined, cannot continue\n");
abort (); #endif
}
/* If two times can be observed less than half a clock tick apart, then assume "get" is microsecond accurate.
Two times only 1 microsecond apart are not believed, since some kernels take it upon themselves to ensure gettimeofday doesn't return the same value twice, for the benefit of applications using it for a timestamp. This is obviously very stupid given the speed of CPUs these days.
Making "reps" many calls to noop_1() is designed to waste some CPU, with a view to getting measurements 2 microseconds (or more) apart. "reps" is increased progressively until such a period is seen.
The outer loop "attempts" are just to allow for any random nonsense or system load upsetting the measurements (ie. making two successive calls to "get" come out as a longer interval than normal).
Bugs:
The assumption that any interval less than a half tick implies microsecond resolution is obviously fairly rash, the true resolution could be anything between a microsecond and that half tick. Perhaps something special would have to be done on a system where this is the case, since there's no obvious reliable way to detect it
automatically. */
#define MICROSECONDS_P(name, type, get, sec, usec) \
{ \ staticint result = -1; \
type st, et; \ long dt, half_tick; \ unsigned attempt, reps, i, j; \
\ if (result != -1) \ return result; \
\
result = 0; \
half_tick = (1000000L / clk_tck ()) / 2; \
\ for (attempt = 0; attempt < 5; attempt++) \
{ \
reps = 0; \ for (;;) \
{ \
get (st); \ for (i = 0; i < reps; i++) \ for (j = 0; j < 100; j++) \
noop_1 (CNST_LIMB(0)); \
get (et); \
\
dt = (sec(et)-sec(st))*1000000L + usec(et)-usec(st); \
\ if (speed_option_verbose >= 2) \
printf ("%s attempt=%u, reps=%u, dt=%ld\n", \
name, attempt, reps, dt); \
\ if (dt >= 2) \ break; \
\
reps = (reps == 0 ? 1 : 2*reps); \ if (reps == 0) \ break; /* uint overflow, not normal */ \
} \
\ if (dt < half_tick) \
{ \
result = 1; \ break; \
} \
} \
\ if (speed_option_verbose) \
{ \ if (result) \
printf ("%s is microsecond accurate\n", name); \ else \
printf ("%s is only %s clock tick accurate\n", \
name, unittime_string (1.0/clk_tck())); \
} \ return result; \
}
/* Test whether getrusage goes backwards, return non-zero if it does (suggesting it's flawed).
On a macintosh m68040-unknown-netbsd1.4.1 getrusage looks like it's microsecond accurate, but has been seen remaining unchanged after many microseconds have elapsed. It also regularly goes backwards by 1000 to 5000 usecs, this has been seen after between 500 and 4000 attempts taking perhaps 0.03 seconds. We consider this too broken for good measuring. We used to have configure pretend getrusage didn't exist on this system, but a runtime test should be more reliable, since we imagine the problem
is not confined to just this exact system tuple. */
int
getrusage_backwards_p (void)
{ staticint result = -1; struct rusage start, prev, next; long d; int i;
result = 0;
i = 0; for (;;)
{
memcpy (&prev, &next, sizeof (prev));
getrusage (0, &next);
if (next.ru_utime.tv_sec < prev.ru_utime.tv_sec
|| (next.ru_utime.tv_sec == prev.ru_utime.tv_sec
&& next.ru_utime.tv_usec < prev.ru_utime.tv_usec))
{ if (speed_option_verbose)
printf ("getrusage went backwards (attempt %d: %ld.%06ld -> %ld.%06ld)\n",
i,
(long) prev.ru_utime.tv_sec, (long) prev.ru_utime.tv_usec,
(long) next.ru_utime.tv_sec, (long) next.ru_utime.tv_usec);
result = 1; break;
}
/* minimum 1000 attempts, then stop after either 0.1 seconds or 50000
attempts, whichever comes first */
d = 1000000 * (next.ru_utime.tv_sec - start.ru_utime.tv_sec)
+ (next.ru_utime.tv_usec - start.ru_utime.tv_usec);
i++; if (i > 50000 || (i > 1000 && d > 100000)) break;
}
return result;
}
/* CLOCK_PROCESS_CPUTIME_ID looks like it's going to be in a future version of glibc (some time post 2.2).
CLOCK_VIRTUAL is process time, available in BSD systems (though sometimes
defined, but returning -1 for an error). */
int
cgt_works_p (void)
{ staticint result = -1;
struct_timespec unit;
if (! have_cgt) return 0;
if (! have_cgt_id)
{ if (speed_option_verbose)
printf ("clock_gettime don't know what ID to use\n");
result = 0; return result;
}
if (result != -1) return result;
/* trial run to see if it works */ if (clock_gettime (CGT_ID, &unit) != 0)
{ if (speed_option_verbose)
printf ("clock_gettime id=%d error: %s\n", CGT_ID, strerror (errno));
result = 0; return result;
}
/* get the resolution */ if (clock_getres (CGT_ID, &unit) != 0)
{ if (speed_option_verbose)
printf ("clock_getres id=%d error: %s\n", CGT_ID, strerror (errno));
result = 0; return result;
}
cgt_unittime = unit.tv_sec + unit.tv_nsec * 1e-9; if (speed_option_verbose)
printf ("clock_gettime is %s accurate\n", unittime_string (cgt_unittime));
if (cgt_unittime < 10e-9)
{ /* Do we believe this? */ struct timespec start, end; staticvolatileint counter; double duration; if (clock_gettime (CGT_ID, &start))
{ if (speed_option_verbose)
printf ("clock_gettime id=%d error: %s\n", CGT_ID, strerror (errno));
result = 0; return result;
} /* Loop of at least 1000 memory accesses, ought to take at
least 100 ns*/ for (counter = 0; counter < CGT_DELAY_COUNT; counter++)
; if (clock_gettime (CGT_ID, &end))
{ if (speed_option_verbose)
printf ("clock_gettime id=%d error: %s\n", CGT_ID, strerror (errno));
result = 0; return result;
}
duration = (end.tv_sec + end.tv_nsec * 1e-9
- start.tv_sec - start.tv_nsec * 1e-9); if (speed_option_verbose)
printf ("delay loop of %d rounds took %s (according to clock_gettime)\n",
CGT_DELAY_COUNT, unittime_string (duration)); if (duration < 100e-9)
{ if (speed_option_verbose)
printf ("clock_gettime id=%d not believable\n", CGT_ID);
result = 0; return result;
}
}
result = 1; return result;
}
/* suppress a warning about a[] unused */
a[0] = 0;
if (! have_mftb) return 0;
#ifdef SIGILL
old_handler = signal (SIGILL, mftb_works_handler); if (old_handler == SIG_ERR)
{ if (speed_option_verbose)
printf ("mftb_works_p(): SIGILL not supported, assuming mftb works\n"); return 1;
} if (setjmp (mftb_works_buf))
{ if (speed_option_verbose)
printf ("mftb_works_p(): SIGILL during mftb, so doesn't work\n"); return 0;
}
MFTB (a);
signal (SIGILL, old_handler); if (speed_option_verbose)
printf ("mftb_works_p(): mftb works\n"); #else
if (speed_option_verbose)
printf ("mftb_works_p(): SIGILL not defined, assuming mftb works\n"); #endif
#if ! HAVE_GETTIMEOFDAY if (speed_option_verbose)
printf ("mftb_works_p(): no gettimeofday available to measure mftb\n"); return 0; #endif
/* The time base is normally 1/4 of the bus speed on 6xx and 7xx chips, on
other chips it can be driven from an external clock. */
cycletime = freq_measure ("mftb", freq_measure_mftb_one); if (cycletime == -1.0)
{ if (speed_option_verbose)
printf ("mftb_works_p(): cannot measure mftb period\n"); return 0;
}
mftb_unittime = cycletime; return 1;
}
volatileunsigned *sgi_addr;
int
sgi_works_p (void)
{ #if HAVE_SYSSGI && HAVE_MMAP staticint result = -1;
phys = syssgi (SGI_QUERY_CYCLECNTR, &period_picoseconds); if (phys == (__psunsigned_t) -1)
{ /* ENODEV is the error when a counter is not available */ if (speed_option_verbose)
printf ("syssgi SGI_QUERY_CYCLECNTR error: %s\n", strerror (errno));
result = 0; return result;
}
sgi_unittime = period_picoseconds * 1e-12;
/* IRIX 5 doesn't have SGI_CYCLECNTR_SIZE, assume 32 bits in that case. Challenge/ONYX hardware has a 64 bit byte counter, but there seems no
obvious way to identify that without SGI_CYCLECNTR_SIZE. */ #ifdef SGI_CYCLECNTR_SIZE
size = syssgi (SGI_CYCLECNTR_SIZE); if (size == -1)
{ if (speed_option_verbose)
{
printf ("syssgi SGI_CYCLECNTR_SIZE error: %s\n", strerror (errno));
printf (" will assume size==4\n");
}
size = 32;
} #else
size = 32; #endif
if (size < 32)
{
printf ("syssgi SGI_CYCLECNTR_SIZE gives %d, expected 32 or 64\n", size);
result = 0; return result;
}
/* only used if a supplementary method is chosen below */
cycles_limit = (have_cycles == 1 ? M_2POW32 : M_2POW64) / 2.0
* speed_cycletime;
if (have_grus && getrusage_microseconds_p() && ! getrusage_backwards_p())
{ /* this is a good combination */
use_grus = 1;
supplement_unittime = grus_unittime = 1.0e-6;
strcpy (speed_time_string, "CPU cycle counter, supplemented by microsecond getrusage()");
} elseif (have_cycles == 1)
{ /* When speed_cyclecounter has a limited range, look for something
to supplement it. */ if (have_gtod && gettimeofday_microseconds_p())
{
use_gtod = 1;
supplement_unittime = gtod_unittime = 1.0e-6;
strcpy (speed_time_string, "CPU cycle counter, supplemented by microsecond gettimeofday()");
} elseif (have_grus)
{
use_grus = 1;
supplement_unittime = grus_unittime = 1.0 / (double) clk_tck ();
sprintf (speed_time_string, "CPU cycle counter, supplemented by %s clock tick getrusage()", unittime_string (supplement_unittime));
} elseif (have_times)
{
use_times = 1;
supplement_unittime = times_unittime = 1.0 / (double) clk_tck ();
sprintf (speed_time_string, "CPU cycle counter, supplemented by %s clock tick times()", unittime_string (supplement_unittime));
} elseif (have_gtod)
{
use_gtod = 1;
supplement_unittime = gtod_unittime = 1.0 / (double) clk_tck ();
sprintf (speed_time_string, "CPU cycle counter, supplemented by %s clock tick gettimeofday()", unittime_string (supplement_unittime));
} else
{
fprintf (stderr, "WARNING: cycle counter is 32 bits and there's no other functions.\n");
fprintf (stderr, " Wraparounds may produce bad results on long measurements.\n");
}
}
if (use_grus || use_times || use_gtod)
{ /* must know cycle period to compare cycles to other measuring
(via cycles_limit) */
speed_cycletime_need_seconds ();
d = end[0] - start[0];
t = (double) d - (d > end[0] ? M_2POW32 : 0.0);
t += (end[1] - start[1]) * M_2POW32; return t;
}
/* Calculate the difference between "start" and "end" using fields "sec" and "psec", where each "psec" is a "punit" of a second.
The seconds parts are allowed to cancel before being combined with the psec parts, in case a simple "sec+psec*punit" exceeds the precision of a double.
Total time is only calculated in a "double" since an integer count of psecs might overflow. 2^32 microseconds is only a bit over an hour, or 2^32 nanoseconds only about 4 seconds.
The casts to "long" are for the benefit of timebasestruct_t, where the
fields are only "unsigned int", but we want a signed difference. */
/* This is for use after time_base_to_time, ie. for seconds and nanoseconds. */ double
timebasestruct_diff_secs (const timebasestruct_t *end, const timebasestruct_t *start)
{
DIFF_SECS_ROUTINE (tb_high, tb_low, 1e-9);
}
double
speed_endtime (void)
{ #define END_USE(name,value) \ do { \ if (speed_option_verbose >= 3) \
printf ("speed_endtime(): used %s\n", name); \
result = value; \ goto done; \
} while (0)
#define END_ENOUGH(name,value) \ do { \ if (speed_option_verbose >= 3) \
printf ("speed_endtime(): %s gives enough precision\n", name); \
result = value; \ goto done; \
} while (0)
#define END_EXCEED(name,value) \ do { \ if (speed_option_verbose >= 3) \
printf ("speed_endtime(): cycle counter limit exceeded, used %s\n", \
name); \
result = value; \ goto done; \
} while (0)
if (use_grus)
{
t_grus = rusage_diff_secs (&end_grus, &start_grus);
/* Use getrusage() if the cycle counter limit would be exceeded, or if
it provides enough accuracy already. */ if (use_cycles)
{ if (t_grus >= speed_precision*grus_unittime)
END_ENOUGH ("getrusage()", t_grus); if (t_grus >= cycles_limit)
END_EXCEED ("getrusage()", t_grus);
}
}
if (use_times)
{
t_times = (end_times.tms_utime - start_times.tms_utime) * times_unittime;
/* Use times() if the cycle counter limit would be exceeded, or if
it provides enough accuracy already. */ if (use_cycles)
{ if (t_times >= speed_precision*times_unittime)
END_ENOUGH ("times()", t_times); if (t_times >= cycles_limit)
END_EXCEED ("times()", t_times);
}
}
if (use_gtod)
{
t_gtod = timeval_diff_secs (&end_gtod, &start_gtod);
/* Use gettimeofday() if it measured a value bigger than the cycle
counter can handle. */ if (use_cycles)
{ if (t_gtod >= cycles_limit)
END_EXCEED ("gettimeofday()", t_gtod);
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.