with regular function:
#include <iostream>
#include <chrono>
using std::cout;
//timer
using A = std::chrono::steady_clock;
using B = std::chrono::duration<double,std::ratio<1>>;
using C = std::chrono::time_point<A>;
C timer{A::now()};
double elap(C x){return std::chrono::duration_cast<B>(A::now()-timer).count();}
//counter
int count{0};
//recursive function
void repeat() {
cout<<++count<<" - "<<elap(timer)<<'s'<<'n';
repeat();
cout<<"test";
}
int main() {repeat();}
this prints till there’s an overflow, the last line I get is “174372 – 1.00188s”
with a lambda:
#include <iostream>
#include <chrono>
using std::cout;
//timer
using A = std::chrono::steady_clock;
using B = std::chrono::duration<double,std::ratio<1>>;
using C = std::chrono::time_point<A>;
C timer{A::now()};
double elap(C x){return std::chrono::duration_cast<B>(A::now()-timer).count();}
//counter
int count{0};
int main() {
//lambda definition
auto repeat=[](this auto repeat) -> void {
cout<<++count<<" - "<<elap(timer)<<'s'<<'n';
repeat();
cout<<"test";
};
repeat();
}
this prints till there’s an overflow, the last line I get is “1220751 – 7.18137s”.
on the line 174372 (where the regular function stop printing) I get the following: “174372 – 0.988323s”
There’s not a huge different in speed, but a big one on how much longer the recursive lambda call lasted compared to the regular recursive one. I suppose the lambda calls allocate less memory, what would be the reason for such behavior?
Tried to call two equivalent recurse functions (a lambda and a regular one), I got different results.
Compiler: gcc 14.2.1
Flags: -std=c++23 -O2 -DNDEBUG`
OS: Arch Linux (kernel 6.12.1)
CPU: Intel i5-1135G7
link to godbolt (regular function): https://godbolt.org/z/azsxoaMxE
link to godbolt (lambda): https://godbolt.org/z/WajW3PhWP
user15 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
9