有没有办法在 C++ 函数中获取函数名?

2022-01-11 00:00:00 profiling macros c++

我想实现一个函数跟踪器,它会跟踪一个函数执行的时间.我有以下相同的课程:-

I want to implement a function tracer, which would trace how much time a function is taking to execute. I have following class for the same:-

class FuncTracer
{
    public:
        FuncTracer(LPCTSTR strFuncName_in)
        {
            m_strFuncName[0] = _T('');
            if( strFuncName_in ||
                _T('') != strFuncName_in[0])
            {   
                _tcscpy(m_strFuncName,strFuncName_in);

                TCHAR strLog[MAX_PATH];
                _stprintf(strLog,_T("Entering Func:- <%s>"),m_strFuncName);
                LOG(strLog)

                m_dwEnterTime = GetTickCount();
            }
        }

        ~FuncTracer()
        {
            TCHAR strLog[MAX_PATH];
            _stprintf(strLog,_T("Leaving Func:- <%s>, Time inside the func <%d> ms"),m_strFuncName, GetTickCount()-m_dwEnterTime);
            LOG(strLog)
        }

    private:
        TCHAR m_strFuncName[MAX_PATH];
        DWORD m_dwEnterTime;
};

void TestClass::TestFunction()
{
    // I want to avoid writing the function name maually..
    // Is there any macro (__LINE__)or some other way to 
    // get the function name inside a function ??

    FuncTracer(_T("TestClass::TestFunction"));
    /*
     * Rest of the function code.
     */
}

我想知道是否有任何方法可以从函数内部获取函数的名称?基本上我希望我班级的用户简单地创建一个相同的对象.他们可能不会传递函数名.

I want to know if there is any way to get the name of the function from inside of a function? Basically I want the users of my class to simply create an object the same. They may not pass the function name.

推荐答案

VC++有

__FUNCTION__ for undecorated names

__FUNCDNAME__ for decorated names

你可以编写一个宏,它自己会分配一个对象,并在构造函数中传递名称转换宏.有点喜欢

And you can write a macro that will itself allocate an object and pass the name-yelding macro inside the constructor. Smth like

#define ALLOC_LOGGER FuncTracer ____tracer( __FUNCTION__ );

相关文章