Can*_*pus 26 c++ macros profiling
我想实现一个函数跟踪器,它将跟踪一个函数执行的时间.我有以下课程: -
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.
*/
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有任何方法可以从函数内部获取函数的名称?基本上我希望我班级的用户只需创建一个相同的对象.它们可能无法传递函数名称.
bk1*_*k1e 51
C99有__func__,但对于C++,这将是编译器特定的.从好的方面来说,一些特定于编译器的版本提供了额外的类型信息,当你在一个模板化的函数/类中进行跟踪时,这种信息特别好.
Boost库BOOST_CURRENT_FUNCTION为头文件boost/current_function.hpp中的大多数C++编译器定义了宏.如果编译器太旧而不支持,则结果为"(未知)".
sha*_*oth 23
VC++有
__FUNCTION__ for undecorated names
Run Code Online (Sandbox Code Playgroud)
和
__FUNCDNAME__ for decorated names
Run Code Online (Sandbox Code Playgroud)
你可以编写一个宏,它将自己分配一个对象并在构造函数中传递name-yelding宏.Smth喜欢
#define ALLOC_LOGGER FuncTracer ____tracer( __FUNCTION__ );
Run Code Online (Sandbox Code Playgroud)
Cir*_*四事件 13
C++20 std::source_location::function_name
这基本上正是你想要的。
https://en.cppreference.com/w/cpp/utility/source_location声明用法如下:
#include <iostream>
#include <string_view>
#include <source_location>
void log(std::string_view message,
const std::source_location& location = std::source_location::current()
) {
std::cout << "info:"
<< location.file_name() << ":"
<< location.line() << ":"
<< location.function_name() << " "
<< message << '\n';
}
int main() {
log("Hello world!");
}
Run Code Online (Sandbox Code Playgroud)
可能的输出:
info:main.cpp:16:main Hello world!
Run Code Online (Sandbox Code Playgroud)
所以请注意呼叫如何保留呼叫者信息,因此我们看到所需的main呼叫位置而不是log。
我已经更详细地介绍了相关标准:__PRETTY_FUNCTION__、__FUNCTION__、__func__ 之间有什么区别?