]> www.ginac.de Git - ginac.git/blob - check/timer.cpp
Extend copyright to 2011.
[ginac.git] / check / timer.cpp
1 /** @file timer.cpp
2  *
3  *  A simple stop watch class. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2011 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  */
22
23 #ifdef HAVE_RUSAGE
24 #include <sys/resource.h>
25 #include <unistd.h>
26 #include <sys/time.h>
27 #else
28 #include <ctime>
29 #endif
30
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
34 #include "timer.h"
35
36 timer::timer() : on(false)
37 {
38 #ifdef HAVE_RUSAGE
39         getrusage(RUSAGE_SELF, &used1);
40         used2.ru_utime = used1.ru_utime;
41         used2.ru_stime = used1.ru_stime;
42 #else
43         used1 = clock();
44         used2 = used1;
45 #endif
46 }
47
48 void timer::start()
49 {
50         on = true;
51 #ifdef HAVE_RUSAGE
52         getrusage(RUSAGE_SELF, &used1);
53         used2.ru_utime = used1.ru_utime;
54         used2.ru_stime = used1.ru_stime;
55 #else
56         used1 = clock();
57         used2 = used1;
58 #endif
59 }
60
61 void timer::stop()
62 {
63         on = false;
64 #ifdef HAVE_RUSAGE
65         getrusage(RUSAGE_SELF, &used2);
66 #else
67         used2 = clock();
68 #endif
69 }
70
71 void timer::reset()
72 {
73 #ifdef HAVE_RUSAGE
74         getrusage(RUSAGE_SELF, &used1);
75         used2.ru_utime = used1.ru_utime;
76         used2.ru_stime = used1.ru_stime;
77 #else
78         used1 = clock();
79         used2 = used1;
80 #endif
81 }
82
83 double timer::read()
84 {
85         double elapsed;
86 #ifdef HAVE_RUSAGE
87         if (running())
88                 getrusage(RUSAGE_SELF, &used2);
89         return ((used2.ru_utime.tv_sec - used1.ru_utime.tv_sec) +
90                 (used2.ru_stime.tv_sec - used1.ru_stime.tv_sec) +
91                 (used2.ru_utime.tv_usec - used1.ru_utime.tv_usec) * 1e-6 +
92                 (used2.ru_stime.tv_usec - used1.ru_stime.tv_usec) * 1e-6);
93 #else
94         if (running())
95                 used2 = clock();
96         return double(used2 - used1)/CLOCKS_PER_SEC;
97 #endif
98 }
99
100 bool timer::running()
101 {
102         return on;
103 }