Skip to content

Instantly share code, notes, and snippets.

@ZJUGuoShuai
Last active October 24, 2023 11:44
Show Gist options
  • Select an option

  • Save ZJUGuoShuai/faba123e554da6fcac5f93613ea5e9c1 to your computer and use it in GitHub Desktop.

Select an option

Save ZJUGuoShuai/faba123e554da6fcac5f93613ea5e9c1 to your computer and use it in GitHub Desktop.
用于方便地测量代码运行时间的 C++ class Timer
//
// 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 */
@ZJUGuoShuai

ZJUGuoShuai commented Jul 31, 2023

Copy link
Copy Markdown
Author

使用方法:

Timer::Get()->Start("Job 1");
// ...
// Job 1 code
// ...
Timer::Get()->End("Job 1");

Print the summary:

Timer::Get()->PrintMeanTimes(10);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment