虚拟功能与CRTP

时间:2014-10-23 14:09:58

标签: c++ performance crtp

我正在尝试使用VS2010对虚拟功能和CRTP进行简单的测量测试,VS2010是一个简单的控制台程序,其中,我写入文本文件10,000次,有时我在发布版本中观察到的我正在通过CTRL + F5运行IDE(无需调试启动),我看到虚拟函数调用带来了显着的性能提升,但同时,当我通过Windows资源管理器作为管理员运行程序时,我看到了一个重大的性能提升CRTP,我真的很好奇为什么会这样。我的代码如下: -

class CFileProfile
{

public:
CFileProfile()
{
    if(!m_file.Open(_T("C:\\File_logger_opt.txt") , CFile::modeCreate|CFile::modeWrite))
    {
        printf("\n Error In Opening File \n");
    }
}

~CFileProfile()
{
    m_file.Close();
}

static CFileProfile* GetDefault()
{
    if(m_pMe == NULL)
    {
      m_pMe = new CFileProfile;
    }

    return m_pMe;

}

static void ReleaseDefault()
{
    if(m_pMe)
    {
        delete m_pMe;m_pMe = NULL;
    }
}

CStdioFile* GetFile()
{
    return &m_file;
}

static  CFileProfile* m_pMe;
CStdioFile m_file;

};

template<typename CRTP_ARGS>
class CBase_CRTP
{
public:
void Execute()
{
    CRTP_ARGS::ExecuteA();
}
    };


class CDerived_CRTP : public CBase_CRTP<CDerived_CRTP>
{
public:
   static void ExecuteA()
{
    CString sLine;
    sLine.Format(_T("\n Executing CDerived_CRTP \n"));
    CFileProfile::GetDefault()->GetFile()->WriteString(sLine);

}
};

class CBase_WCRTP
{
public:
virtual void Execute()
{

}
};


class CDerived_WCRTP :public CBase_WCRTP
{
public:
virtual void Execute()
{
    CString sLine;
    sLine.Format(_T("\n Executing CDerived_WCRTP \n"));
    CFileProfile::GetDefault()->GetFile()->WriteString(sLine);
}
};


Inside Main:-
    CFileProfile::GetDefault();

SYSTEMTIME sys_time;
::GetSystemTime(&sys_time);
CString sLine;
sLine.Format(_T("\n The Virtual Start :-[%d:%d:%d:%d] \n") , sys_time.wHour , sys_time.wMinute , sys_time.wSecond,sys_time.wMilliseconds);
CFileProfile::GetDefault()->GetFile()->WriteString(sLine);

CDerived_WCRTP wcrtp;
for(int i = 0; i < 10000; i++)
{
    wcrtp.Execute();
}

::GetSystemTime(&sys_time);
sLine.Format(_T("\n The Virtual End :-[%d:%d:%d:%d] \n") , sys_time.wHour , sys_time.wMinute , sys_time.wSecond,sys_time.wMilliseconds);
CFileProfile::GetDefault()->GetFile()->WriteString(sLine);



::GetSystemTime(&sys_time);
sLine.Format(_T("\n The  CRTP Start :-[%d:%d:%d:%d] \n") , sys_time.wHour , sys_time.wMinute , sys_time.wSecond,sys_time.wMilliseconds);
CFileProfile::GetDefault()->GetFile()->WriteString(sLine);

CDerived_CRTP crtp;
for(int i = 0; i < 10000; i++)
{
    crtp.Execute();
}

::GetSystemTime(&sys_time);
sLine.Format(_T("\n The  CRTP End :-[%d:%d:%d:%d] \n") , sys_time.wHour , sys_time.wMinute , sys_time.wSecond,sys_time.wMilliseconds);
CFileProfile::GetDefault()->GetFile()->WriteString(sLine);



CFileProfile::ReleaseDefault();

0 个答案:

没有答案