gtsam_points
Loading...
Searching...
No Matches
easy_profiler.hpp
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2021 Kenji Koide (k.koide@aist.go.jp)
3
4#pragma once
5
6#include <chrono>
7#include <vector>
8#include <fstream>
9#include <iostream>
10
11namespace gtsam_points {
12
14public:
15 EasyProfiler(const std::string& prof_label, std::ostream& ost) : EasyProfiler(prof_label, true, false, ost) {}
16
17 EasyProfiler(const std::string& prof_label, bool enabled = true, bool debug = false, std::ostream& ost = std::cout)
18 : enabled(enabled),
19 debug(debug),
20 prof_label(prof_label),
21 ost(ost) {
22 if (!enabled) {
23 return;
24 }
25
26 labels.push_back("begin");
27 times.push_back(std::chrono::high_resolution_clock::now());
28
29 if (debug) {
30 ost << "--- " << prof_label << " (debug) ---" << std::endl;
31 }
32 }
33
35 if (!enabled) {
36 return;
37 }
38
39 labels.push_back("end");
40 times.push_back(std::chrono::high_resolution_clock::now());
41
42 ost << "--- " << prof_label << " ---" << '\n';
43
44 int longest = 0;
45 for (const auto& label : labels) {
46 longest = std::max<int>(label.size(), longest);
47 }
48
49 for (int i = 1; i < labels.size(); i++) {
50 std::vector<char> pad(longest - labels[i - 1].size(), ' ');
51 std::string label = labels[i - 1] + std::string(pad.begin(), pad.end());
52
53 ost << label << ":" << std::chrono::duration_cast<std::chrono::nanoseconds>(times[i] - times[i - 1]).count() / 1e6 << "[msec]" << '\n';
54 }
55
56 ost << "total:" << std::chrono::duration_cast<std::chrono::nanoseconds>(times.back() - times.front()).count() / 1e6 << "[msec]" << '\n';
57 ost << std::flush;
58 }
59
60 void push(const std::string& label) {
61 if (!enabled) {
62 return;
63 }
64
65 labels.push_back(label);
66 times.push_back(std::chrono::high_resolution_clock::now());
67
68 if (debug) {
69 ost << ">> " << label << " (" << std::chrono::duration_cast<std::chrono::nanoseconds>(times.back() - times.front()).count() / 1e6 << "[msec])"
70 << std::endl;
71 }
72 }
73
74private:
75 const bool enabled;
76 const bool debug;
77 const std::string prof_label;
78
79 std::vector<std::string> labels;
80 std::vector<std::chrono::high_resolution_clock::time_point> times;
81
82 std::ostream& ost;
83 std::ofstream ofs;
84};
85} // namespace gtsam_points
Definition easy_profiler.hpp:13