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