Home > Backend Development > C++ > body text

How to measure the execution time of a function in C?

WBOY
Release: 2023-08-28 14:21:06
forward
963 people have browsed it

How to measure the execution time of a function in C?

Here we will see how to calculate the time spent by a process. For this problem, we will use the clock() function. The clock() function is located in the time.h header file.

To get the elapsed time, we can use clock() to get the time at the beginning of the task, use clock() again to get the time at the end of the task, and then subtract the two values ​​to get the difference. We then divide the difference by CLOCK_PER_SEC (clock ticks per second) to get the processor time.

Example

#include <stdio.h>
#include <time.h>
void take_enter() {
   printf("Press enter to stop the counter </p><p>");
   while(1) {
      if (getchar())
      break;
   }
}
main() {
   // Calculate the time taken by take_enter()
   clock_t t;
   t = clock();
   printf("Timer starts</p><p>");
   take_enter();
   printf("Timer ends </p><p>");
   t = clock() - t;
   double time_taken = ((double)t)/CLOCKS_PER_SEC; // calculate the elapsed time
   printf("The program took %f seconds to execute", time_taken);
}
Copy after login

Output

Timer starts
Press enter to stop the counter
Timer ends
The program took 5.218000 seconds to execute
Copy after login

The above is the detailed content of How to measure the execution time of a function in C?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!