gpt4 book ai didi

c++ - 在类实例或方法的上下文中调用函数以进行性能分析

转载 作者:行者123 更新时间:2023-11-28 01:50:04 25 4
gpt4 key购买 nike

性能分析题:有没有办法在类的上下文或类的方法中执行函数?

我想分析特定逻辑段的性能。我的设想是这样的

(免责声明:粗略的例子只是为了说明一点。不会编译)。

const int DEBUG_LEVEL = 7;

class PerfWrapper {
public:
PerfWrapper(int f) {} // Constructor: take function as argument
void invoke() {} // Invoke the function passed as argument
double execution_time() {
begin = std::chrono::high_resolution_clock::now();
// etc..
}
double memory_usage() {}
private:
}
int foo() {
int sum{0}
for (int i=0; i<1000; ++i)
for (int j=0; j<MAX; ++j)
sum += i * j;
return sum;
}
int main() {
if (DEBUG_LEVEL = 7)
PerfWrapper p(foo); // Create an instance, passing foo as an argument

// below foo() is called in context of the performance wrapper
int myTime = p.invoke().execution_time(); // Invokes foo in context of p and tracks execution time
int myMemory = p.invoke().memory_usage(); // Same, except gathering memory usage info.
// etc..
}
}

这里我们有 PerfWrapper 类。实例化时,对象上的结果方法能够接受函数作为参数,并在类的上下文中执行函数。它将进行性能测量,其结果可通过界面访问。

注意“DEBUG_LEVEL”设置。如果需要性能分析,则只需将 DEBUG_LEVEL 设置为 7。

你见过这样的吗?如果不是,如何最好地完成分析?我知道这似乎有点离谱,但希望不会那么多。谢谢,基思 :^)

最佳答案

也许您正在寻找函数指针,它可以按以下简化代码所示使用:

typedef int(*aFooFunctionType)(void);

class PerformanceTest {
public:
PerformanceTest(aFooFunctionType fooFuncPtr) { m_fooFuncPtr = fooFuncPtr; }
void test() {
int x = m_fooFuncPtr();
// do something with x (or not...)
};
private:
aFooFunctionType m_fooFuncPtr;
};


int fooFunc(void) {
return 100;
}

int main(int argc, char* argv[]) {

PerformanceTest pTest(fooFunc);
pTest.test();
return 0;
}

关于c++ - 在类实例或方法的上下文中调用函数以进行性能分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43379814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com