gpt4 book ai didi

c++ - CPU 使用率高

转载 作者:可可西里 更新时间:2023-11-01 11:09:08 24 4
gpt4 key购买 nike

我们正在使用以下方法将日志写入日志文件。日志条目保存在名为 m_LogList 的 vector 中(STL 字符串条目保存在 vector 中)。当vector的大小大于100时调用该方法。如果调用FlushLog方法,Log服务器的CPU占用率在20-40%左右。如果我们注释掉 FlushLog 方法,CPU 利用率会下降到 10-20% 的范围。
我可以使用哪些优化来降低 CPU 利用率?我们使用 fstream 对象将日志条目写入文件

void CLogFileWriter::FlushLog()
{
CRCCriticalSectionLock lock(m_pFileCriticalSection);
//Entire content of the vector are writing to the file
if(0 < m_LogList.size())
{
for (int i = 0; i < (int)m_LogList.size(); ++i)
{
m_ofstreamLogFile << m_LogList[i].c_str()<<endl;
m_nSize = m_ofstreamLogFile.tellp();

if(m_pLogMngr->NeedsToBackupFile(m_nSize))
{
// Backup the log file
}
}

m_ofstreamLogFile.flush();
m_LogList.clear(); //Clearing the content of the Log List
}
}

最佳答案

我要使用的第一个优化是删除 .c_str()<< m_LogList[i].c_str() .它强制operator<<做一个strlen (O(n)) 而不是依赖 string::size (O(1))。

此外,我只是对字符串大小求和,而不是调用 tellp .

最后,<< endl包括同花顺,在每一行。只需使用 << '\n' .你在最后已经有了同花顺。

关于c++ - CPU 使用率高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9925278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com