Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ How to measure and compare execution time between two functions

I’m new to C++

And I’m trying to build a simple project, so I need to measure and compare execution time between two functions, to see which one is better for performance time,

I know there are a lot of ways like calculating start and end time and calc difference
But that’s not usually true, so there’s no right way to do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my old code:

#include <chrono>

auto begin = std::chrono::steady_clock::now();
/* some code*/
auto end = std::chrono::steady_clock::now();

auto time = (end - begin).count();

Any help please?

>Solution :

using C++ Timeit library:

Compare Time Between Two Functions

void func1() { /* some code */ }
void func2() { /* some code */ }

compareit(1000,func1,func2);

result

[COMPARE IT] first(675)  > second(22) x30

NOTES

first means first function func1()

second means second function func2()

x30 means the func2() faster than func1() by 30 times

675 22 it is a elapsed time to execute func1,func2 for 1000 times


Measure Time For One Function

void func() { for (auto i = 0; i < 10; i++) sqrt(i); }
std::cout << timeit(1000, func).nanoseconds() << std::endl;

result

225451
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading