3 Timing.c Measuring Program running time
5 This module contains functions for measuring program running time.
7 Copyright (C) 2004, Wong Chi Kwong.
9 This program is free software; you can redistribute it and/or
10 modify it under the terms of the GNU General Public License
11 as published by the Free Software Foundation; either version 2
12 of the License, or (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
30 #include <sys/resource.h>
42 double setStartTime() {
46 double usertime
, systime
;
49 getrusage(RUSAGE_SELF
, &usage
);
51 usertime
= (double)usage
.ru_utime
.tv_sec
+ (double)usage
.ru_utime
.tv_usec
/ 1000000.0;
52 systime
= (double)usage
.ru_stime
.tv_sec
+ (double)usage
.ru_stime
.tv_usec
/ 1000000.0;
54 return(usertime
+ systime
);
59 return (double)clock() / (double)CLOCKS_PER_SEC
;
64 gettimeofday(&tp
, NULL
);
65 return (double)tp
.tv_sec
+ (double)tp
.tv_usec
/ (double)1000000;
72 double getElapsedTime(double startTime
) {
76 double usertime
, systime
;
79 getrusage(RUSAGE_SELF
, &usage
);
81 usertime
= (double)usage
.ru_utime
.tv_sec
+ (double)usage
.ru_utime
.tv_usec
/ 1000000.0;
82 systime
= (double)usage
.ru_stime
.tv_sec
+ (double)usage
.ru_stime
.tv_usec
/ 1000000.0;
84 return (usertime
+ systime
) - startTime
;
89 return (double)clock() / (double)CLOCKS_PER_SEC
- startTime
;
94 gettimeofday(&tp
, NULL
);
95 return (double)tp
.tv_sec
+ (double)tp
.tv_usec
/ (double)1000000 - startTime
;
102 void printElapsedTime(FILE *file
, const int printHour
, const int printMin
, const int printSec
,
103 const int secNumberOfDecimal
, const double seconds
) {
105 printElapsedTimeNoNewLine(file
, printHour
, printMin
, printSec
, 0, secNumberOfDecimal
, seconds
);
110 void printElapsedTimeNoNewLine(FILE *file
, const int printHour
, const int printMin
, const int printSec
,
111 const int secMinPrintLength
, const int secNumberOfDecimal
, const double seconds
) {
115 char secondDisplay
[8] = "%0.0f s";
118 if (printHour
&& !printMin
&& printSec
) {
119 fprintf(stderr
, "printElapsedTime(): Cannot skip minute only!\n");
122 if (secNumberOfDecimal
> 9) {
123 fprintf(stderr
, "printElapsedTime(): secNumberOfDecimal > 9!\n");
128 secondDisplay
[1] = secondDisplay
[1] + (char)secMinPrintLength
;
129 secondDisplay
[3] = secondDisplay
[3] + (char)secNumberOfDecimal
;
132 min
= (int)(seconds
/ 60);
133 if (!printSec
&& printMin
) {
134 if (seconds
- min
* 60 >= 30) {
154 fprintf(file
, "%d h ", hour
);
157 fprintf(file
, "%d m ", min
);
160 fprintf(file
, secondDisplay
, sec
);