Skip to main content

Using time() functions in C programs to calculate time taken to execute set of statements

Following is the procedure to use time() functions in C. These functions help us to calculate total time taken (in seconds) to execute a set of statements. This is very helpful if we are testing the efficiency of any algorithm / methodology:

  1. Include time.h header in your C program. i.e., write #include<time.h> statement before main() function.
  2. Inside main(), define two variables t1 and t2 whose data type is time_t. i.e, write time_t t1, t2; t1 is used to record initial time (in seconds) and t2 is used to record elapsed time (in seconds)
  3. Use t1=time(NULL); before the start of the algorithm/ methodology that you want to test.
  4. After writing algorithm/ methodology, use t2=time(NULL); 
  5. Total time taken can now be calculated as: t2-t1. Following sample example shows the usage of time() functions in C programs:

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

main()
{
        time_t t1, t2;
        int flag=0;
        unsigned long long int i, j, n;

        printf("Enter N:\n");
        scanf("%llu", &n);
        t1=time(NULL);
        for(i=2;i<=n;i++)
        {
                flag=0;
                for(j=2;j<=(i-1);j++)
                {
                        if(i%j==0)
                        {
                                flag=1;
                                break;
                        }
                }
                if(flag==0)
                  printf("%llu\n", i);
        }
        t2=time(NULL);
        printf("Time taken (in seconds): %d\n", t2-t1);
}

Execute the above program by providing large values of N and note the time it takes (in seconds) to generate prime numbers between 2-N.

Comments

Popular posts from this blog

Conduction of Lab IA-1 for PSPC Lab

PSPC Lab IA-1 shall be conducted next week (i.e., between 08/10/2018 and 13/10/2018) during the regular lab slots (i.e., on  09/10/2018 - Tuesday - C2 Batch - 2:30 - 5:00 P.M. and on  11/10/2018 - Thursday - C1 Batch - 10:30 - 1:00 P.M. ) Procedure for conducting Lab Internals: ONLY one common problem definition shall be given to the entire batch during the lab internal. ONLY one answer sheet (4 pages) shall be provided to each student. Write the C program for the problem definition in the answer sheet provided. Show the write-up to the teacher and get it singed. Students will be allowed to execute the program only after getting the signature on the answer sheet. Separate logins shall be provided for each student during the lab internal. Hence don't login using regular logins. During lab internals, bringing mobile phones is STRICTLY PROHIBITED. However, students can bring the text book "Programming in ANSI C" by E. Balagurusamy to the lab. Students can use ...