Skip to content

Instantly share code, notes, and snippets.

@abikoushi
Last active June 27, 2025 05:23
Show Gist options
  • Save abikoushi/f9f6f2ceb244f581f425e1ab7955e202 to your computer and use it in GitHub Desktop.
Save abikoushi/f9f6f2ceb244f581f425e1ab7955e202 to your computer and use it in GitHub Desktop.
Block-wise computational time evaluation for Rcpp
#include <chrono>
#include <iostream>
#include <fstream>
#include <mutex>
class TimerLogger {
public:
TimerLogger(const std::string& label, const std::string& filename = "timelog.csv")
: label_(label), filename_(filename) {
start_ = std::chrono::high_resolution_clock::now();
}
~TimerLogger() {
auto end = std::chrono::high_resolution_clock::now();
double elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start_).count() / 1000.0;
log_to_csv(label_, elapsed);
}
private:
std::string label_;
std::string filename_;
std::chrono::high_resolution_clock::time_point start_;
static void log_to_csv(const std::string& label, double elapsed) {
static std::mutex mtx; // スレッドセーフにするため
std::lock_guard<std::mutex> lock(mtx);
erLo {
public:
TimerLogger(const std::string& label, const std::string& filename = "timelog.csv")
: label_(label), filename_(filename) {
start_ = std::chrono::high_resolution_clock::now();
}
~TimerLogger() {
auto end = std::chrono::high_resolution_clock::now();
double elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start_).count() / 1000.0;
log_to_csv(label_, elapsed);
}
private:
std::string label_;
std::string filename_;
std::chrono::high_resolution_clock::time_point start_;
static void log_to_csv(const std::string& label, double elapsed) {
static std::mutex mtx; // スレッドセーフにするため
std::lock_guard<std::mutex> lock(mtx);
std::ofstream ofs("timelog.csv", std::ios::app); // append モード
if (ofs.is_open()) {
ofs << label << "," << elapsed << "\n";
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment