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('\0'); if( strFuncName_in || _T('\0') != 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.
Put all the functions you want to select from into a dll, then use dlsym (or GetProcAddress on Windows, or whatever other API your system offers) to get the function pointer by name, and call using that.
You cannot get the name of the function in C++, but you can print the pointer and later check the binary (if not stripped) for the function name. The signature can be printed exactly as you are doing, just that the type name is not really 'human readable'.
Every function has a name by which it is known to the rest of the program. The name of a function in C can be anything from a single letter to a long word. The ANSI Standard, however, only guarantees that C will be able to distinguish the first 31 letters of identifiers , or function and variable names.
C99 has __func__
, but for C++ this will be compiler specific. On the plus side, some of the compiler-specific versions provide additional type information, which is particularly nice when you're tracing inside a templatized function/class.
__FUNCTION__
, __FUNCDNAME__
, __FUNCSIG__
__func__
, __FUNCTION__
, __PRETTY_FUNCTION__
Boost library has defined macro BOOST_CURRENT_FUNCTION
for most C++ compilers in header boost/current_function.hpp. If the compiler is too old to support this, the result will be "(unknown)".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With