Last active
October 24, 2023 11:44
-
-
Save ZJUGuoShuai/faba123e554da6fcac5f93613ea5e9c1 to your computer and use it in GitHub Desktop.
用于方便地测量代码运行时间的 C++ class Timer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // Timer.h | |
| // NLE | |
| // | |
| // Created by Guo Shuai on 2023/7/27. | |
| // | |
| #ifndef Timer_h | |
| #define Timer_h | |
| #include <chrono> | |
| #include <iostream> | |
| #include <string> | |
| #include <map> | |
| #define TIMER_LOG 0 | |
| class Timer { | |
| struct Stat { | |
| std::chrono::time_point<std::chrono::high_resolution_clock> start; | |
| long long total_duration = 0; | |
| long long mean_duration = 0; | |
| int count = 0; | |
| }; | |
| public: | |
| // Get the Timer Singleton | |
| static Timer* Get() { | |
| static Timer timer; | |
| return &timer; | |
| } | |
| // Print all mean durations | |
| void PrintMeanTimes(int n) { | |
| for (const auto& [name, stat] : stats_) { | |
| #if TIMER_LOG | |
| printf("[Timer Summary] %s mean time: %lldms\n", name.c_str(), stat.total_duration / (1000 * n)); | |
| #endif | |
| } | |
| } | |
| void Start(const std::string& name) { | |
| stats_[name].start = std::chrono::high_resolution_clock::now(); | |
| } | |
| void End(const std::string& name) { | |
| auto end = std::chrono::high_resolution_clock::now(); | |
| auto start = stats_[name].start; | |
| long long duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count(); | |
| stats_[name].total_duration += duration; | |
| stats_[name].count++; | |
| #if TIMER_LOG | |
| printf("[Timer] %s time: %lldms\n", name.c_str(), duration / 1000); | |
| #endif | |
| } | |
| private: | |
| std::map<std::string, Stat> stats_; | |
| }; | |
| #endif /* Timer_h */ |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使用方法:
Print the summary: