Logging improvements to allow prettier displays in the server GUI.
[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 #include "i18n.h"
30
31 using namespace std;
32
33 /** @param n Name to use when giving output */
34 PeriodTimer::PeriodTimer (string n)
35         : _name (n)
36 {
37         gettimeofday (&_start, 0);
38 }
39
40 /** Destroy PeriodTimer and output the time elapsed since its construction */
41 PeriodTimer::~PeriodTimer ()
42 {
43         struct timeval stop;
44         gettimeofday (&stop, 0);
45         cout << N_("T: ") << _name << N_(": ") << (seconds (stop) - seconds (_start)) << N_("\n");
46 }
47
48 /** @param n Name to use when giving output.
49  *  @param s Initial state.
50  */
51 StateTimer::StateTimer (string n, string s)
52         : _name (n)
53 {
54         struct timeval t;
55         gettimeofday (&t, 0);
56         _time = seconds (t);
57         _state = s;
58 }
59
60 /** @param s New state that the caller is in */
61 void
62 StateTimer::set_state (string s)
63 {
64         double const last = _time;
65         struct timeval t;
66         gettimeofday (&t, 0);
67         _time = seconds (t);
68
69         if (_totals.find (s) == _totals.end ()) {
70                 _totals[s] = 0;
71         }
72
73         _totals[_state] += _time - last;
74         _state = s;
75 }
76
77 /** Destroy StateTimer and generate a summary of the state timings on cout */
78 StateTimer::~StateTimer ()
79 {
80         if (_state.empty ()) {
81                 return;
82         }
83
84
85         set_state (N_(""));
86
87         cout << _name << N_(":\n");
88         for (map<string, double>::iterator i = _totals.begin(); i != _totals.end(); ++i) {
89                 cout << N_("\t") << i->first << " " << i->second << N_("\n");
90         }
91 }