I want my getEnd function to return a closure with start saved.
When I call this closure it should return time difference...
How to implement it in the c++?
Something like followed:
using namespace std;
long microtime() {
timeval time;
gettimeofday(&time, NULL);
long microsec = ((unsigned long long)time.tv_sec * 1000000) + time.tv_usec;
return microsec;
}
std::function<void()> getEnd (){
long start = microtime();
long end() {
return microtime() - start;
}
return end;
};
#include <functional>
std::function<long()> getEnd()
{
long const start = microtime();
return [=]{ return microtime() - start; };
}
Please note that the above will allocate memory on the heap, so for most practical applications a better alternative would be
struct timer {
long const start;
timer(): start(microtime()) {}
long operator()() { return microtime - start(); }
};
timer getEnd() { return timer(); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.