Move things round a bit.
[dcpomatic.git] / src / lib / timer.cc
1 /*
2     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /** @file src/timer.cc
21  *  @brief Some timing classes for debugging and profiling.
22  */
23
24 #include <iostream>
25 #include <sys/time.h>
26 #include "timer.h"
27 #include "util.h"
28
29 using namespace std;
30
31 /** @param n Name to use when giving output */
32 PeriodTimer::PeriodTimer (string n)
33         : _name (n)
34 {
35         gettimeofday (&_start, 0);
36 }
37
38 /** Destroy PeriodTimer and output the time elapsed since its construction */
39 PeriodTimer::~PeriodTimer ()
40 {
41         struct timeval stop;
42         gettimeofday (&stop, 0);
43         cout << "T: " << _name << ": " << (seconds (stop) - seconds (_start)) << "\n";
44 }
45
46 /** @param n Name to use when giving output.
47  *  @param s Initial state.
48  */
49 StateTimer::StateTimer (string n, string s)
50         : _name (n)
51 {
52         struct timeval t;
53         gettimeofday (&t, 0);
54         _time = seconds (t);
55         _state = s;
56 }
57
58 /** @param s New state that the caller is in */
59 void
60 StateTimer::set_state (string s)
61 {
62         double const last = _time;
63         struct timeval t;
64         gettimeofday (&t, 0);
65         _time = seconds (t);
66
67         if (_totals.find (s) == _totals.end ()) {
68                 _totals[s] = 0;
69         }
70
71         _totals[_state] += _time - last;
72         _state = s;
73 }
74
75 /** Destroy StateTimer and generate a summary of the state timings on cout */
76 StateTimer::~StateTimer ()
77 {
78         if (_state.empty ()) {
79                 return;
80         }
81
82         
83         set_state ("");
84
85         cout << _name << ":\n";
86         for (map<string, double>::iterator i = _totals.begin(); i != _totals.end(); ++i) {
87                 cout << "\t" << i->first << " " << i->second << "\n";
88         }
89 }