TinyChatEngine
Loading...
Searching...
No Matches
profiler.h
1#include <chrono>
2#include <iostream>
3#include <map>
4#include <string>
5
6class Profiler {
7 public:
8 bool for_demo = false;
9 static Profiler& getInstance() {
10 static Profiler instance;
11 return instance;
12 }
13
14 void start(const std::string& section) { start_times[section] = std::chrono::high_resolution_clock::now(); }
15
16 void start(const std::string& section, const long long section_flops) {
17 start_times[section] = std::chrono::high_resolution_clock::now();
18 if (flops.count(section) == 0)
19 flops[section] = section_flops;
20 else
21 flops[section] += section_flops;
22 }
23
24 void reset() {
25 start_times.clear();
26 durations.clear();
27 counts.clear();
28 flops.clear();
29 }
30
31 void stop(const std::string& section) {
32 auto end_time = std::chrono::high_resolution_clock::now();
33 auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_times[section]).count();
34 durations[section] += duration;
35 counts[section]++;
36 }
37
38 void report_internal() const {
39 if (for_demo) {
40 for (const auto& entry : durations) {
41 std::string row;
42 std::cout << entry.first + ", ";
43 float s = (float)(entry.second) / 1000000;
44 float ts = (float)counts.at(entry.first);
45 printf("Total time: %.1f s, %.1f ms/token, %.1f token/s, %d tokens\n\n", s, s / ts * 1000, ts / s,
46 counts.at(entry.first));
47 }
48 } else {
49 std::cout << "Section, Total time(us), Average time(us), Count, GOPs:" << std::endl;
50 for (const auto& entry : durations) {
51 std::string row;
52 row += entry.first + ", ";
53 row += std::to_string(entry.second) + ", ";
54 row += std::to_string(entry.second / counts.at(entry.first)) + ", ";
55 if (flops.count(entry.first) == 0)
56 row += std::to_string(counts.at(entry.first)) + ", N/A";
57 else {
58 row += std::to_string(counts.at(entry.first)) + ", ";
59 // ops and microsecond
60 row += std::to_string((((float)flops.at(entry.first)) / (float)(entry.second)) / 1000.0);
61 }
62 std::cout << row << std::endl;
63 }
64 }
65 }
66
67 void report() const {
68#ifdef PROFILER
69 report_internal();
70#endif
71 }
72
73 private:
74 Profiler() {}
75 Profiler(const Profiler&) = delete;
76 Profiler& operator=(const Profiler&) = delete;
77
78 std::map<std::string, std::chrono::high_resolution_clock::time_point> start_times;
79 std::map<std::string, long long> flops;
80 std::map<std::string, long long> durations;
81 std::map<std::string, int> counts;
82};
Definition profiler.h:6