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