which functions should use to calculate the time of a function Is there any built-in function for this purpose.
CodePudding user response:
You can use this code:
auto a = chrono::steady_clock::now();
//write your code here
auto b = chrono::steady_clock::now();
double time = chrono::duration <double, milli> (b - a).count();
cout << endl << "Time ---> " << time;
CodePudding user response:
There's nothing built in specifically for calculating the time taken by a function.
There are functions built in to retrieve the current time. See std::chrono::high_resolution_clock::now()
for more details about that.
To time a function, you'd (at least normally) retrieve the current time just after entering the function, and again just before exiting.
You can then subtract the two, and use std::duration_cast
to convert that to a duration in terms of period that's convenient (milliseconds, microseconds, or nanoseconds, as the case may be).
Putting those together, you could (for example) get something like this:
template <class T, class U, template<class, class> class F, typename ...Args>
auto timer(F<T,U> f, std::string const &label, Args && ...args) {
using namespace std::chrono;
auto start = high_resolution_clock::now();
auto holder = f(std::forward<Args>(args)...);
auto stop = high_resolution_clock::now();
std::cout << label << " time: " << duration_cast<microseconds>(stop - start).count() << "\n";
return holder;
}
This lets you pass some arbitrary function (and arguments to be passed to that function) and prints out the time the function took to execute. At the moment it's doing microseconds, but changing that to milliseconds should be trivial.
At the end, this returns whatever value the called function produced, so if you had something like:
x = f(a, b, c);
You could replace that with:
x = timer(f, a, b, c);
...to get the time consumed by f
printed out.