×

How to measure time taken by a function in C?

Measuring the time taken by a function is quite a complex task, because numerous methods are frequently not transferable to other platforms, measuring the execution time of a C programs or of certain parts of it can sometimes be more difficult than it should be. The best way to use will mostly depends on your operating system, compiler version, and what you mean by "time."

Two important things to be noted while measuring the time are:

Simply said, wall time - also referred to as clock time or wall-clock time - is the entire amount of time that passed during the measurement. Given that you can start and stop the stopwatch accurately at the desired execution moments, it is the amount of time you can measure with one.

Inversely, CPU Time describes the period of time when the CPU was working to process the program's instructions. The CPU time does not account for the time spent waiting for other processes, such as I/O activities, to finish.

Importance of measuring time: If you’re going to evaluate performance you have to measure something, you can tell if you have improved. If a program can do the same thing in less execution time, then it can be considered more efficient, doing the same with less resources.

In simple words, measuring time of a function or a program is a measure of how long an algorithm takes to run in relation to the size of the input.

It calculates how long it takes for each algorithm's code statement to run. In other words, it is efficient, or how long a program function takes to process a given input.

Therefore, it’s highly important to know measuring time of a function or a program which ultimately results in improving the efficiency of thast particular function or program.

There are many methods available in calculating the time taken by a function. One of the methods is to use clock() function.

Clock() function is available in time.h header file.

Syntax:

clock_t begin = clock();


/* here, do your time-consuming job */


clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

Let’s see some programs to understand better:

Example 1:

#include <stdio.h>
#include <time.h>
int main(){
    clock_t start = clock();
    clock_t stop = clock();
    double elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
    printf("Time elapsed in ms: %f", elapsed);
}

Output:

How to measure time taken by a function in C

The output won’t be constant and charges from time to time.

Example 2:

#include <stdio.h>
#include <time.h>       // for clock_t, clock(), CLOCKS_PER_SEC
#include <unistd.h>     // for sleep()
 int main()
{
    double time_spent = 0.0;
     clock_t begin = clock();
 
    sleep(3);
 
    clock_t end = clock();
    time_spent += (double)(end - begin) / CLOCKS_PER_SEC;
 
    printf("The elapsed time is %f seconds", time_spent);
 
    return 0;
}

Output:

How to measure time taken by a function in C

The sleep() function enables users to wait for a running thread for a specified amount of time. While the sleep() function will put the current executable to sleep for the amount of time specified by the thread, other CPU operations will continue to run smoothly.

Example 3:

#include <stdio.h>
#include <time.h>
void fun()
{
    printf("fun() starts \n");
    printf("Press enter any key to stop function \n");
    while(1)
    {
        if (getchar())
            break;
    }
    printf("fun() ends \n");
}
int main()
{
    clock_t ti;
    ti = clock();
    fun();
    ti = clock() - ti;
    double time = ((double)ti)/CLOCKS_PER_SEC; 
 
    printf("fun() took %f seconds to execute \n", time);
    return 0;
}

Output:

How to measure time taken by a function in C

Also, it’s important to know various types of times which have to be considered, while measuring the time if a program/function.

Computer science words such as "compile," "load," and "execution times" all refer to the various phases of running software programs.

Build Time

The process of converting computer programs and code into a form that the CPU can understand, or machine-readable code, is known as compile-time. A compiler usually accomplishes this. Code in the source language is converted to a particular target language at build time.

Syntax and semantic analysis are a couple common tasks carried out at compile time. The assignment of specific computer program instructions to certain physical memory locations is another feature of compile time.

Load Period

The term "load time" describes the stage at which all the programs are loaded into memory with the aid of a loader and is typically followed by.

The software is also ready for the execution phase at load time. Reading the program's instructions and making sure any resources required for execution are ready are a few tasks carried out during this period.

Process Time

It’s a specific stage at which the commands in computer programs or code are carried out is referred to as execution time. Run-time libraries are utilized during execution. Reading programs instructions to perform tasks or complete activities is one of the fundamental operations that take place at execution time.

How measuring time of a function or a program helps in real life:

To measure efficiency of a computer program:

Dozens of companies have come up with “metrics” to measure performance - and none of them truly encapsulate the “value” of a programmer to the company.

For example:

You could count the number of lines of code they write per month. But terrible programmers need more lines of code to do the job that a good programmer can code more succinctly - more efficiently.

You could try to break up a project into “difficulty points” and count the number of “difficulty points” each programmer deals with per month. But it’s notoriously hard to align the actual difficulty of a problem from one team to another - so you really don’t get any kind of absolute count that works.

Counting the number of bugs fixed is an interesting approach - but it’s hard to cope with an occasional bug that turns out to be horribly hard to fix compared to some that turn out to be unexpectedly trivial.

In the end, what companies that I’ve worked for do is to combine three documents in an “annual review” process:

1. The lead engineer’s report on the programmer.

2. A “peer review” written by a co-worker who is picked at random.

3. A “self-review” where the programmer writes their own review.

Each person lists the big successes and the big difficulties for the person being reviewed.

The team manager collects those three reports - tries to generate a coherent picture from it - which turns into a combined review. The programmer and the manager read through it together - and perhaps tweak the wording and sign the resulting document as a “true record” of the year. These are used to decide for each person whether they performed better than expected, worse than expected or about right.

Those who met expectations get an inflation-linked and experience-based pay rise.

Conclusion:

Therefore, measuring the time of any program or a function gives us an idea of word time, execution time, process time etc. It really makes a huge difference understanding the concepts of those time. Time is one of the most valuable resources known to humans. Its limited availability is what makes it precious. Time management is crucial because it enables you to accomplish more in less time hence increasing your efficiency.


Related Topics

Types of Array in C

What is an Array? One value can be stored in a variable at once. How many variables will you need if you have 100 values? Well, the answer isn't 100. It...

14 minutes read.

What is algorithm in C?

What is an algorithm? In computer programming languages, an algorithm is set of statement that solves a particular problem. In C, first step of every algorithm is Start and last step of...

3 minutes read.

How to open a C file on android mobile

A C file is a file that has a .c extension and contains code written in the C language. C is a computer programming language developed by Dennis Ritchie at...

4 minutes read.

Compilation Process in C language

What is the Compilation Process?  The compilation is a method whereby the source code is converted into object code. It is achieved with compiler assistance. The compiler tests the source code for syntactic...

3 minutes read.

How to Calculate Time Complexity in C?

What is time complexity? An algorithm's time complexity measures how long it takes to complete a task in relation to the size of the input. It should be noted that the...

5 minutes read.

Multiplication Table in C

Displaying table up to 10 #include <stdio.h> int main() {     int num, i = 1;     printf("     Enter any Number:");     scanf("%d", &num);     printf("Multiplication table of %d: ", num);  ...

1 minute read.

Find the Largest Three Distinct Elements in an Array using C/C++

In this tutorial, we will demonstrate how to use a C/C++ programme to locate the highest three different elements in an array. C/C++ Program to Find the Largest Three Different Elements...

3 minutes read.

Variable Declaration in C

What is a Variable? A Variable is nothing more than a name for a memory place where data/information can be stored. Any alphabet (from a to z or A to Z), the...

4 minutes read.

How to get ASCII value in C

For text data on computers and the internet, ASCII (American Standard Code for Information Interchange). It is the most widely used character encoding standard. One hundred twenty-eight alphabetic, numeric, special...

3 minutes read.

Multi-dimensional Arrays in C

Multi-dimensional Arrays in C The C programming allows the concept of multi-dimensional arrays. The data within the multidimensional arrays are stored in the tabular form, that is, in a row significant...

3 minutes read.

GPA Calculator in C

GPA stands for Grade Point Average. This GPA is used to measure the student's academic performance in educational institutes. By using this, segregation takes place and lets us know how...

4 minutes read.

Pyramid Pattern in C

Pyramid Pattern in C A pyramid is a polyhedron created by connecting a base that will be a polygon, and all the lateral faces are triangles. All the bases are connected...

5 minutes read.

For Loop in C

The Syntax of For Loop for (initialization statement; test expression; update statement) {     /* main body of the FOR loop */ } How does For loop work? In for loop, the initialization command is...

3 minutes read.

Built-in functions in C

The function is a set of instructions and statements enclosed in the "{}" delimiter. In c, there are two types of functions. Pre-define functions/ Built-in functionsUser define function. Built-in functions in C:- These...

8 minutes read.

Nested if-else statement in C

If we use an if-else statement within another if statement in a C program, it is called a nested if-else statement in C. It helps to check the condition inside...

3 minutes read.

GCD program of two numbers in C

GCD stands for Greatest Common Divisor, which is also known as Highest Common Factor, which can be abbreviated as HCF. Mathematically it can be defined as any two positive integers...

3 minutes read.

Infinite loop in C

Definition of infinite loop The infinite loop is a loop that does not get dismissed because of its looping construct. A continuous output or no output are the two possible outcomes...

3 minutes read.

Palindrome Number in C

What is a Palindrome? A number that doesn't change when reversed is known as a palindrome. We reverse a number and compare it to the original number to determine whether it is...

4 minutes read.

C Program to Find the Largest Number using Ternary Operator

In this tutorial, we will write some program to determine which of the provided integers is larger using the ternary operator, also known as the conditional operator in C. Ternary Operator: The ternary...

3 minutes read.

C vs Java Strings

String in C In C, we can define a string as a bunch of characters. A character array is distinguished from a string by the presence of the special character '\0'...

5 minutes read.