在C++ debug模式下,一些集成开发环境(IDE)也提供了自带的控制台输出窗口来显示程序的运行结果。在Visual Studio中,可以使用OutputDebugString
函数将输出信息打印到“输出”窗口。
打印年月日
void debugPrint(int nSendOrder)
{
auto now = std::chrono::system_clock::now();
// 转换为时间字符串
time_t t = std::chrono::system_clock::to_time_t(now);
char buf[26];
ctime_s(buf, sizeof buf, &t);
// 去掉末尾的换行符
buf[24] = '\0';
CStringA bufstr(buf);
CStringA tempstr;
tempstr.Format(" SendThread : send id %d , send queue size is %d\n", nSendOrder, m_pSendQueue->size());
bufstr = "---------------------------" + bufstr + tempstr;
// 输出到调试器
OutputDebugStringA(bufstr);
}
输出为:
---------------------------Mon Sep 18 09:49:45 2023 SendThread : send id 1 , send queue size is 9
打印时间精确到毫秒
void debugPrint(CStringA tempstr)
{
auto now = std::chrono::system_clock::now();
// 转换为时间字符串
auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
auto t = std::chrono::system_clock::to_time_t(now_ms);
std::stringstream ss;
ss << std::put_time(std::localtime(&t), "%Y-%m-%d %H:%M:%S");
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now_ms.time_since_epoch()) % 1000;
ss << '.' << std::setfill('0') << std::setw(3) << milliseconds.count();
std::string buf = ss.str();
CStringA bufstr(buf.c_str());
bufstr = "================================== time: " + bufstr + " " + tempstr + "==================================\n";
// 输出到调试器
OutputDebugStringA(bufstr);
}
输出:time: 2023-09-15 11:34:16.532