- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to measure time taken by a function in C?
Here we will see how to calculate the time taken by the process. For this problem, we will use the clock() function. The clock() is present in the time.h header file.
To get the elapsed time, we can get the time using clock() at the beginning, and at the end of the tasks, then subtract the values to get the differences. After that, we will divide the difference by CLOCK_PER_SEC (Number of 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
"); while(1) { if (getchar()) break; } } main() { // Calculate the time taken by take_enter() clock_t t; t = clock(); printf("Timer starts
"); take_enter(); printf("Timer ends
"); 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); }
Output
Timer starts Press enter to stop the counter Timer ends The program took 5.218000 seconds to execute
- Related Articles
- How to measure the time taken by a function in Java?
- Problem: Time taken by tomatoes to rot in JavaScript
- How to measure elapsed time in python?
- How to measure elapsed time in Java?
- Time taken by savepoint to perform backup in SAP HANA
- How to measure the execution time in Golang?
- How to measure execution time for a Java method?
- How to measure actual MySQL query time?
- How do we measure time?
- How to measure time with high-precision in Python?
- How to measure elapsed time in nanoseconds with Java?
- Measure execution time with high precision in C/C++
- Find time taken for signal to reach all positions in a string - C++
- Find time taken for signal to reach all positions in a string in C++
- How to obtain the time taken for a method to be executed in TestNG?

Advertisements