I wish to create ScopePrinter
that works similar as Microsoft's Concurrency::diagnostic::span
,
but it can also detect encapsulating scope.
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]"
Here is my MCVE.
fib()
and fibPrint()
are just a dummy expensive function.
ScopePrinter(X)
is my utility for printing [begin X]
at the constructor and print [end X]
when its block is ended.
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
}
};
Here is the 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();
}
Here is a possible output :-
[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]
How to make ScopePrinter("a31")
's constructor and destructor print full scope like [start a3/a31]
and [end a3/a31]
instead of [start a31]
and [end a31]
?
This will be very useful for profiling my multithreading program.
I am considering thread_local
and MACRO, but I don't think it would help.
I have read Is using std::async many times for small tasks performance friendly?.