How to measure time taken by a function in C?
To calculate time taken by a process, we can use clock() function which is available time.h. We can call the clock function at the beginning and end of the code for which we measure time, subtract the values, and then divide by CLOCKS_PER_SEC (the number of clock ticks per second) to get processor time, like following.
clock_t start, end;
start = clock();
... /* Do the work. */
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
Following is a sample C program where we measure time taken by fun(). The function fun() waits for enter key press to terminate.
"fun() starts \n"
"Press enter to stop fun \n"
"fun() ends \n"
() - t;
time_taken = ((
"fun() took %f seconds to execute \n"
Output: The following output is obtained after waiting for around 4 seconds and then hitting enter key.
Press enter to stop fun
fun() took 4.017000 seconds to execute
Time Complexity: O(1)
Auxiliary Space: O(1)
How to find time taken by a command/program on Linux Shell? References: http://www.gnu.org/software/libc/manual/html_node/CPU-Time.html http://www.cplusplus.com/reference/ctime/clock/?kw=clock Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!