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