C program to calculate total elapsed time by program/function

In this program, we are going to learn how to calculate the total elapsed time by a function/program i.e., the time taken to process the set of statements, complete function or complete program in C programming language?

Program

Below is the C code to calculate total elapsed time by a program or function:

// C program to calculate total elapsed time
// by program/ function.

#include <stdio.h>
#include <time.h>

int main()
{
    time_t prg_begin, prg_end;
    char str[100];

    prg_begin = clock();
    
    printf("Enter any string :");
    gets(str);
    printf("Entered value is :%s\n", str);
    
    prg_end = clock();
    
    printf("%f seconds taken by this program...", (double)(prg_end - prg_begin) / (double)CLK_TCK);
    
    return 0;
}

Output

Enter any string :www.includehelp.com
Entered value is :www.includehelp.com
4.865000 seconds taken by this program...

Explanation

  • clock() : Returns number of clock ticks since program start.
  • clock_t : Type returned by clock() function.
  • CLK_TCK : Number of ticks in a second.
Note

To determine the time in seconds, divide the value returned by clock by the value of the macro CLK_TCK. You can also use CLOCKS_PER_SEC instead of CLK_TCK.

C Miscellaneous Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.