]> git.tdb.fi Git - libs/core.git/blob - source/debug/profiler.h
7a82c5631899699cb42d04773bbf6e4c9ec5b4e9
[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 Data can be recorded by creating a ProfilingScope object in the scope to be
22 profiled.
23
24 Note: This is not thread-safe.  To profile multiple threads, create a separate
25 Profiler for each thread.
26 */
27 class Profiler
28 {
29 public:
30         struct CallInfo
31         {
32                 Msp::Time::TimeStamp entry_time;
33                 Msp::Time::TimeDelta duration;
34         };
35
36         struct ScopeInfo
37         {
38                 Time::TimeStamp first_call;
39                 unsigned calls;
40                 Time::TimeDelta total_time;
41                 Time::TimeDelta self_time;
42                 Time::TimeDelta avg_time;
43                 float calls_per_sec;
44                 std::vector<CallInfo> history;
45                 unsigned hist_pos;
46                 bool hist_full;
47                 std::map<std::string, unsigned> called_from;
48
49                 ScopeInfo();
50         };
51
52 private:
53         unsigned period;
54         std::map<std::string, ScopeInfo> scopes;
55         ProfilingScope *inner;
56
57 public:
58         Profiler();
59
60         /** Sets the averaging period for timing data, measured in calls.  Previous
61         average timings are cleared. */
62         void set_period(unsigned p);
63
64         /** Adds a scope without recording any calls to it.  Useful if you might
65         need to access a scope before it has finished for the first time. */
66         void add_scope(const std::string &name);
67
68         /** Changes the recorded innermost scope pointer and returns the old one.
69         This is used by ProfilingScope to track child time and should not be called
70         manually. */
71         ProfilingScope *enter(ProfilingScope *ps);
72
73         /** Records the data from a ProfilingScope.  It is not useful to call this
74         manually. */
75         void record(const ProfilingScope &);
76
77         /** Returns informations about a scope. */
78         const ScopeInfo &get_scope(const std::string &) const;
79 };
80
81 } // namespace Debug
82 } // namespace Msp
83
84 #endif