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