我希望创建与Microsoft's ScopePrinter
类似的Concurrency::diagnostic::span
,
但它也可以检测封装范围。
ScopePrint sc2{"scope1"}; // should print "[start scope1]"
createTask([&](){
ScopePrint sc2{"scope2"}; // should print "[start scope1/scope2]"
//do something expensive (can create more tasks & ScopePrints)
// should print "[end scope1/scope2]"
});
// should print "[end scope1]"
这是我的MCVE。
fib()
和fibPrint()
只是一个虚拟的昂贵函数。ScopePrinter(X)
是我的实用程序,用于在构造函数中打印[begin X]
,并在其块结束时打印[end X]
。int fib(int n) { // just something that burn some CPU cycles
if (n<2) return n;
return fib(n-1) + fib(n-2);
}
void fibPrint(int n) { // just something that burn some CPU cycles
std::cout<<n<<" fib= "<<fib(n)<<std::endl;
}
struct ScopePrinter{ // my Utility class - useful for profiling
std::string name="";
public: ScopePrinter(std::string strP){
name=strP; std::cout<< ("[start "+name +"]\n");
//in real case, it cache current time too
}
public: ~ScopePrinter(){
std::cout<< ("[end "+name +"]\n");
//in real case, it prints total used time too
}
};
这是
main()
:-int main() {
auto a1 = std::async([&](){
ScopePrinter s("a1");
fibPrint(5);
} );
auto a2 = std::async([&](){
ScopePrinter s("a2");
fibPrint(6);
} );
auto a3 = std::async([&](){
ScopePrinter s("a3");
fibPrint(7);
{
auto a31 = std::async([&](){
ScopePrinter s("a31");
fibPrint(8);
} );
auto a32 = std::async([&](){
ScopePrinter s("a32");
fibPrint(9);
} );
}
} );
a1.wait();
}
这是一个可能的输出:-
[start a1]
[start a2]
5 fib= 6 fib= 58
[end a1]
[end a2]
[start a3]
7 fib= 13
[start a31]
8 fib= 21
[end a31]
[start a32]
9 fib= 34
[end a32]
[end a3]
如何使
ScopePrinter("a31")
的构造函数和析构函数打印完整的作用域,如[start a3/a31]
和[end a3/a31]
而不是[start a31]
和[end a31]
?这对于分析我的多线程程序非常有用。
我正在考虑
thread_local
和MACRO,但我认为这不会有所帮助。我已经读过Is using std::async many times for small tasks performance friendly?。
最佳答案
如果希望a3/a31
和a3/a32
显示为子作用域,则只需将指针传递给外部作用域,然后使用它来构建复合名称:
struct ScopePrinter {
std::string name;
public:
ScopePrinter(std::string strP, ScopePrinter* parent = nullptr)
: name((parent ? parent->name + "/" : "") + strP) {
std::cout << ("[start " + name + "]\n");
}
public:
~ScopePrinter() { std::cout << ("[end " + name + "]\n"); }
};
然后,在嵌套调用的情况下,您可以传入外部范围:
auto a3 = std::async([&]() {
ScopePrinter s("a3");
fibPrint(7);
{
auto a31 = std::async([&]() {
ScopePrinter s1("a31", &s);
fibPrint(8);
});
auto a32 = std::async([&]() {
ScopePrinter s2("a32", &s);
fibPrint(9);
});
}
});
然后,将打印类似以下内容:
[start a1]
5 fib= 5
[end a1]
[start a3]
7 fib= [start a2]
6 fib= 138
[end a2]
[start a3/a31]
8 fib= [start a3/a32]
9 fib= 34
[end a3/a32]
21
[end a3/a31]
[end a3]
关于c++ - 重塑Microsoft的Concurrency::diagnostic::span,它也可以检测外部跨度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59140325/