1 | #pragma once |
2 | |
3 | #include <vector> |
4 | #include <mutex> |
5 | |
6 | #include "taichi/common/core.h" |
7 | #include "taichi/system/timer.h" |
8 | |
9 | namespace taichi { |
10 | |
11 | struct TimelineEvent { |
12 | std::string name; |
13 | bool begin; |
14 | float64 time; |
15 | std::string tid; |
16 | |
17 | std::string to_json(); |
18 | }; |
19 | |
20 | class Timeline { |
21 | public: |
22 | Timeline(); |
23 | |
24 | ~Timeline(); |
25 | |
26 | static Timeline &get_this_thread_instance(); |
27 | |
28 | void set_name(const std::string &tid) { |
29 | tid_ = tid; |
30 | } |
31 | |
32 | std::string get_name() { |
33 | return tid_; |
34 | } |
35 | |
36 | void clear(); |
37 | |
38 | void insert_event(const TimelineEvent &e); |
39 | |
40 | std::vector<TimelineEvent> fetch_events(); |
41 | |
42 | class Guard { |
43 | public: |
44 | explicit Guard(const std::string &name); |
45 | |
46 | ~Guard(); |
47 | |
48 | private: |
49 | std::string name_; |
50 | }; |
51 | |
52 | private: |
53 | std::string tid_; |
54 | std::mutex mut_; |
55 | std::vector<TimelineEvent> events_; |
56 | }; |
57 | |
58 | // A timeline system for multi-threaded applications |
59 | class Timelines { |
60 | public: |
61 | static Timelines &get_instance(); |
62 | |
63 | void insert_events(const std::vector<TimelineEvent> &events); |
64 | |
65 | void insert_events_without_locking(const std::vector<TimelineEvent> &events); |
66 | |
67 | void insert_timeline(Timeline *timeline); |
68 | |
69 | void remove_timeline(Timeline *timeline); |
70 | |
71 | void clear(); |
72 | |
73 | void save(const std::string &filename); |
74 | |
75 | bool get_enabled(); |
76 | |
77 | void set_enabled(bool enabled); |
78 | |
79 | private: |
80 | std::mutex mut_; |
81 | std::vector<TimelineEvent> events_; |
82 | std::vector<Timeline *> timelines_; |
83 | bool enabled_{false}; |
84 | }; |
85 | |
86 | #define TI_TIMELINE(name) \ |
87 | taichi::Timeline::Guard _timeline_guard_##__LINE__(name); |
88 | |
89 | #define TI_AUTO_TIMELINE TI_TIMELINE(__FUNCTION__) |
90 | |
91 | } // namespace taichi |
92 | |