Wednesday, December 7, 2016

Find running time of an algorithm in C++

Some times we need to find how long would an algorithm take to complete a task. This is needed very much when we comparing two or more algorithms. So I looked for that in several forums and most of them have suggested to use clock() function which comes with ctime header. That didn't work properly because It gives the time from the start of the program (which I will explain latter part of the post) and not suitable for measuring intervals in nanosecond level.

So here is the solution for that. We can use functions in class high_resolution_clock. Here IsPrime is the function that I want to find the running time of.
As you can see in line 30, we can cast the time difference int any unit we want (ns,ms). That gives us a great advantage of finding very small time intervals. But if we use clock() function instead we wan't be able to achieve that much of accuracy.

Here is a code example of using clock() function (which I don't recommend in this scenario)


clock() function will give the total number of clock ticks until the execution of function from the start of the program (If we want to convert it into seconds, have to divide by CLOCKS_PER_SEC).
But this gives a good result only if we are doing a considerable calculation between the time interval. other wise we will get a zero as result.

No comments:

Post a Comment

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...