Cocreateinstance消耗高cpu

时间:2019-08-28 21:23:45

标签: c++ mfc

我正在使用LOGSERVICELib.dll公开的接口方法作为主项目中的日志记录方法。主项目中有abc.h文件,它在其中创建LOGSERVICELib.dll的实例,并使用它的公开方法记录主项目错误。最近,我观察到它使过程太慢,在对代码进行性能分析后,我发现共同创建实例时会消耗大量cpu以及其他CStdio函数*为什么Cstdio函数会占用大量cpu时间(70-80%)?

        Cstdiofile::Readstring()
        Cstdiofile::writeString()
        Cstdiofile::flush()


LogHelper.h( external .h file)

class LogHelper
{

public:
    LogHelper()
    {
        CoInitialize(NULL);
    };


    ~LogHelper()
    {
        CoUninitialize();
    };

    static void LogMessage(_bstr_t eventName, _bstr_t logFilePath, _bstr_t logFileName, _bstr_t message)
    {
        HRESULT hr = S_OK ;

        try
        {
            CComPtr<LOGSERVICELib::ILogUtility> ILog;
            if(ILog == NULL)
            hr = ILog.CoCreateInstance(__uuidof(LOGSERVICELib::LogUtility));

            if( SUCCEEDED( hr ) )
            {
                hr = pILog->PostMessage( logFilePath, logFileName, eventName, message, L"", L"");           
            }
        }
        catch( _com_error& )
        {
            // forget it
        }


    }}

stdAfx.h(Main project)

#define LOG_THIS(x)     LogHelper::LogMessage( L"Service", _Module.m_bstrLogHelper, _Module.m_LogHelperLogFile, x)


Service.cpp:

void publish()
{
LOG_THIS("published new service");
}

1 个答案:

答案 0 :(得分:1)

        hr = ILog.CoCreateInstance(__uuidof(LOGSERVICELib::LogUtility));

显然,此代码属于LogHelper的构造函数。 Profiler引导了针对获胜的优化,您已经使用了Profiler。对你有益。在使用它时,请完全摆脱f(ILog == NULL)并将声明移到类构造函数中。这样,尝试创建它的代码将始终运行。

CComPtr自动释放对象。

很遗憾,LogMethod当前是static。为了修复性能,可以重构可用的选择,直到不再static或自己实现LOGSERVICELib::LogUtility