2000-06-05 H.J. Lu <hjl@gnu.org>
[binutils.git] / libiberty / getruntime.c
blobb855ea6e82f56c35ceb92b9a8724c4d571f6be66
1 /* Return time used so far, in microseconds.
2 Copyright (C) 1994, 1999 Free Software Foundation, Inc.
4 This file is part of the libiberty library.
5 Libiberty is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
10 Libiberty is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
15 You should have received a copy of the GNU Library General Public
16 License along with libiberty; see the file COPYING.LIB. If
17 not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 #include "config.h"
22 #include "ansidecl.h"
23 #include "libiberty.h"
25 /* There are several ways to get elapsed execution time; unfortunately no
26 single way is available for all host systems, nor are there reliable
27 ways to find out which way is correct for a given host. */
29 #include <time.h>
31 #if defined (HAVE_GETRUSAGE) && defined (HAVE_SYS_RESOURCE_H)
32 #include <sys/time.h>
33 #include <sys/resource.h>
34 #endif
36 #ifdef HAVE_TIMES
37 #ifdef HAVE_SYS_PARAM_H
38 #include <sys/param.h>
39 #endif
40 #include <sys/times.h>
41 #endif
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
47 /* This is a fallback; if wrong, it will likely make obviously wrong
48 results. */
50 #ifndef CLOCKS_PER_SEC
51 #define CLOCKS_PER_SEC 1
52 #endif
54 #ifdef _SC_CLK_TCK
55 #define GNU_HZ sysconf(_SC_CLK_TCK)
56 #else
57 #ifdef HZ
58 #define GNU_HZ HZ
59 #else
60 #ifdef CLOCKS_PER_SEC
61 #define GNU_HZ CLOCKS_PER_SEC
62 #endif
63 #endif
64 #endif
66 long
67 get_run_time ()
69 #if defined (HAVE_GETRUSAGE) && defined (HAVE_SYS_RESOURCE_H)
70 struct rusage rusage;
72 getrusage (0, &rusage);
73 return (rusage.ru_utime.tv_sec * 1000000 + rusage.ru_utime.tv_usec
74 + rusage.ru_stime.tv_sec * 1000000 + rusage.ru_stime.tv_usec);
75 #else /* ! HAVE_GETRUSAGE */
76 #ifdef HAVE_TIMES
77 struct tms tms;
79 times (&tms);
80 return (tms.tms_utime + tms.tms_stime) * (1000000 / GNU_HZ);
81 #else /* ! HAVE_TIMES */
82 /* Fall back on clock and hope it's correctly implemented. */
83 const long clocks_per_sec = CLOCKS_PER_SEC;
84 if (clocks_per_sec <= 1000000)
85 return clock () * (1000000 / clocks_per_sec);
86 else
87 return clock () / clocks_per_sec;
88 #endif /* HAVE_TIMES */
89 #endif /* HAVE_GETRUSAGE */