c++性能分析工具类 统计程序每一步的执行时间
在c++中,经常需要做性能分析,统计 不同的函数,不同的代码块的执行时间,为了方便统计,实现了一个 统计类
有两个函数,第一个是统计从 时间统计类 从初始化到当前调用的次数,第二个是 记录运行了多久,第三个是统计 本次调用和上一次调用的时间差距,并打印当前的时间的年月日时分秒,还自定义地打印一下本次的标记信息。
效果如下
类如下
#include <iostream>
#include <chrono>
#include <vector>
#include <string>
#include <ctime>
#include <iostream>
#include <cmath>
#include <iostream>
#include <sstream>
#include <iomanip>
#ifdef _WIN32
#include <Windows.h>
#endif
class TimeLogger {
public:
TimeLogger() {
start_time = std::chrono::system_clock::now();
previous_time = start_time;
time_number = 0;
}
void get_now_time(std::string show_str = "") {
auto current_time = std::chrono::system_clock::now();
auto time_diff = std::chrono::duration<double>(current_time - previous_time).count();
previous_time = current_time;
std::time_t current_time_t = std::chrono::system_clock::to_time_t(current_time);
std::string current_time_str = std::ctime(¤t_time_t);
SetConsoleOutputCP(65001); // 设置控制台输出编码为 UTF-8
// Remove newline character
if (!current_time_str.empty() && current_time_str[current_time_str.size() - 1] == '\n') {
current_time_str[current_time_str.size() - 1] = '\b'; // Replace '\n' with '\b'
}
if (show_str != "") {
// std::cout << show_str;
std::cout << "[" << time_number<< "\t time--->" <<this->format_float_to_3decimals(this->get_time_since_init())<<"s \t" << " " << time_diff << "s \t" << current_time_str <<" \t"<<show_str<< "]" << std::endl;
}else{
std::cout << "[" << time_number<< "\t time--->" <<this->format_float_to_3decimals(this->get_time_since_init())<<"s \t" << " " << time_diff << "s \t" << current_time_str << "]" << std::endl;
}
time_number++;
}
double get_time_since_init() {
auto current_time = std::chrono::system_clock::now();
auto time_diff = std::chrono::duration<double>(current_time - start_time).count();
// Get current time in time_t format and convert it to a string
std::time_t current_time_t = std::chrono::system_clock::to_time_t(current_time);
std::string current_time_str = std::ctime(¤t_time_t);
// Remove newline character from current_time_str
current_time_str = current_time_str.substr(0, current_time_str.size() - 1);
// Return time difference with 3 decimal points
return std::round(time_diff * 1000) / 1000.0;
}
std::string format_float_to_3decimals(double input_float) {
std::stringstream ss;
ss << std::fixed << std::setprecision(3) << input_float;
std::string formatted_float = ss.str();
// Pad with zeros if necessary
size_t decimal_pos = formatted_float.find(".");
if (decimal_pos != std::string::npos && formatted_float.size() - decimal_pos < 4) {
formatted_float += "0";
}
return formatted_float;
}
private:
std::chrono::time_point<std::chrono::system_clock> start_time;
std::chrono::time_point<std::chrono::system_clock> previous_time;
int time_number;
};
int main() {
TimeLogger logger;
logger.get_now_time("初始化");
for(int i=0;i<=100;i++){
logger.get_now_time("中文修改中 "+std::to_string(i));
Sleep(100);
}
logger.get_time_since_init();
return 0;
}