]> git.tdb.fi Git - libs/core.git/blob - source/debug/profiler.h
f2d5812da30befafb53914168eeb4237c2966b1c
[libs/core.git] / source / debug / profiler.h
1 /* $Id$
2
3 This file is part of libmspcore
4 Copyright © 2007  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #ifndef MSP_DEBUG_PROFILER_H_
9 #define MSP_DEBUG_PROFILER_H_
10
11 #include <map>
12 #include <string>
13 #include <vector>
14 #include "../time/timedelta.h"
15
16 namespace Msp {
17 namespace Debug {
18
19 class ProfilingScope;
20
21 /**
22 A class for collecting timing data from a program.  It's not as efficient as
23 external profilers, but allows profiling of custom scopes and retrieving the
24 profiling data at run time.  An example usage could be showing realtime
25 performance statistics of a game or a simulation.
26
27 See also class ProfilingScope.
28
29 Note: This is not thread-safe.  To profile multiple threads, create a separate
30 Profiler for each thread.
31 */
32 class Profiler
33 {
34 public:
35         struct ScopeInfo
36         {
37                 unsigned calls;
38                 Time::TimeDelta total_time;
39                 Time::TimeDelta self_time;
40                 Time::TimeDelta avg_time;
41                 std::vector<Time::TimeDelta> history;
42                 unsigned hist_pos;
43                 std::map<std::string, unsigned> called_from;
44
45                 ScopeInfo();
46         };
47
48 private:
49         unsigned period;
50         std::map<std::string, ScopeInfo> scopes;
51         ProfilingScope *inner;
52
53 public:
54         Profiler();
55
56         /**
57         Sets the averaging period for timing data, measured in calls.  Previous
58         average timings are cleared.
59         */
60         void set_period(unsigned p);
61
62         /**
63         Adds a scope without recording any calls to it.  Useful if you might need to
64         access a scope before it has finished for the first time.
65         */
66         void add_scope(const std::string &name);
67
68         /**
69         Changes the recorded innermost scope pointer and returns the old one.  This
70         is used by ProfilingScope to track child time and should not be called
71         manually.
72         */
73         ProfilingScope *enter(ProfilingScope *ps);
74
75         /**
76         Records a call to a scope.  You'll probably want to use a ProfilingScope
77         instead of calling this manually.
78
79         @param  sn  Scope name
80         @param  pn  Parent scope name
81         @param  t   Time spent in the scope
82         @param  ct  Time spent in child scopes
83         */
84         void record(const std::string &sn, const std::string &pn, const Time::TimeDelta &t, const Time::TimeDelta &ct);
85
86         /**
87         Returns informations about a scope.
88         */
89         const ScopeInfo &scope(const std::string &) const;
90 };
91
92 } // namespace Debug
93 } // namespace Msp
94
95 #endif