Saturday, November 16, 2024
Google search engine
HomeData Modelling & AIMeasure execution time with high precision in C/C++

Measure execution time with high precision in C/C++

Execution time : The execution time or CPU time of a given task is defined as the time spent by the system executing that task in other way you can say the time during which a program is running. There are multiple way to measure execution time of a program, in this article i will discuss 5 different way to measure execution time of a program.

  1. Using time() function in C & C++.

time() : time() function returns the time since the Epoch(jan 1 1970) in seconds. Header File : “time.h” Prototype / Syntax : time_t time(time_t *tloc); Return Value : On success, the value of time in seconds since the Epoch is returned, on error -1 is returned.

  1. Below program to demonstrate how to measure execution time using time() function. 

CPP




#include <bits/stdc++.h>
using namespace std;
 
// A sample function whose time taken to
// be measured
void fun()
{
    for (int i=0; i<10; i++)
    {
    }
}
 
int main()
{
    /* Time function returns the time since the
        Epoch(jan 1 1970). Returned time is in seconds. */
    time_t start, end;
 
    /* You can call it like this : start = time(NULL);
    in both the way start contain total time in seconds
    since the Epoch. */
    time(&start);
 
    // unsync the I/O of C and C++.
    ios_base::sync_with_stdio(false);
 
    fun();
 
    // Recording end time.
    time(&end);
 
    // Calculating total time taken by the program.
    double time_taken = double(end - start);
    cout << "Time taken by program is : " << fixed
        << time_taken << setprecision(5);
    cout << " sec " << endl;
    return 0;
}


Output:

Time taken by program is : 0.000000 sec

The time complexity of the program is O(1) since it only performs a constant number of operations regardless of the input size. The fun() function has a fixed number of iterations, and the time() function used to measure time also takes constant time.

The space complexity of the program is also constant since it only uses a fixed amount of memory for the integer variables start, end, and time_taken, as well as the cout statement to print the output. Hence, the space complexity is O(1).

  1. Using clock() function in C & C++.

clock() : clock() returns the number of clock ticks elapsed since the program was launched. Header File : “time.h” Prototype / Syntax : clock_t clock(void); Return Value : On success, the value returned is the CPU time used so far as a clock_t; To get the number of seconds used, divide by CLOCKS_PER_SEC.on error -1 is returned.

  1. Below program to demonstrate how to measure execution time using clock() function.you can also see this 

CPP




#include <bits/stdc++.h>
using namespace std;
 
// A sample function whose time taken to
// be measured
void fun()
{
    for (int i=0; i<10; i++)
    {
    }
}
 
int main()
{
    /* clock_t clock(void) returns the number of clock ticks
       elapsed since the program was launched.To get the number
       of seconds used by the CPU, you will need to divide by
       CLOCKS_PER_SEC.where CLOCKS_PER_SEC is 1000000 on typical
       32 bit system.  */
    clock_t start, end;
 
    /* Recording the starting clock tick.*/
    start = clock();
 
    fun();
 
    // Recording the end clock tick.
    end = clock();
 
    // Calculating total time taken by the program.
    double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
    cout << "Time taken by program is : " << fixed
         << time_taken << setprecision(5);
    cout << " sec " << endl;
    return 0;
}


Output:

Time taken by program is : 0.000001 sec

The time complexity of the provided code is O(1), as it simply measures the time required to execute the function fun() using the clock() function from the time library. 

The space complexity of this code is also O(1), as it only declares a few variables on the stack which do not grow with the input size.

  1. using gettimeofday() function in C & C++.

gettimeofday() : The function gettimeofday() can get the time as well as timezone. Header File : “sys/time.h”. Prototype / Syntax : int gettimeofday(struct timeval *tv, struct timezone *tz); The tv argument is a struct timeval and gives the number of seconds and micro seconds since the Epoch. struct timeval { time_t tv_sec; // seconds suseconds_t tv_usec; // microseconds }; Return Value : return 0 for success, or -1 for failure.

  1. Below program to demonstrate how to measure execution time using gettimeofday() function. 

CPP




#include <bits/stdc++.h>
#include <sys/time.h>
using namespace std;
 
// A sample function whose time taken to
// be measured
void fun()
{
    for (int i=0; i<10; i++)
    {
    }
}
 
int main()
{
    /* The function gettimeofday() can get the time as
       well as timezone.
       int gettimeofday(struct timeval *tv, struct timezone *tz);
      The tv argument is a struct timeval and gives the
      number of seconds and micro seconds since the Epoch.
      struct timeval {
               time_t      tv_sec;     // seconds
               suseconds_t tv_usec;    // microseconds
           };    */
    struct timeval start, end;
 
    // start timer.
    gettimeofday(&start, NULL);
 
    // unsync the I/O of C and C++.
    ios_base::sync_with_stdio(false);
 
    fun();
 
    // stop timer.
    gettimeofday(&end, NULL);
 
    // Calculating total time taken by the program.
    double time_taken;
 
    time_taken = (end.tv_sec - start.tv_sec) * 1e6;
    time_taken = (time_taken + (end.tv_usec -
                              start.tv_usec)) * 1e-6;
 
    cout << "Time taken by program is : " << fixed
         << time_taken << setprecision(6);
    cout << " sec" << endl;
    return 0;
}


Output:

Time taken by program is : 0.000029 sec
  1. Using clock_gettime() function in C & C++.

clock_gettime() : The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp. Header File : “time.h”. Prototype / Syntax : int clock_gettime( clockid_t clock_id, struct timespec *tp ); tp parameter points to a structure containing atleast the following members : struct timespec { time_t tv_sec; //seconds long tv_nsec; //nanoseconds }; Return Value : return 0 for success, or -1 for failure. clock_id : clock id = CLOCK_REALTIME, CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC … etc. CLOCK_REALTIME : clock that measures real i.e., wall-clock) time. CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU. CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons).

  1. Below program to demonstrate how to measure execution time using clock_gettime() function. 

CPP




#include <bits/stdc++.h>
#include <sys/time.h>
using namespace std;
 
// A sample function whose time taken to
// be measured
void fun()
{
    for (int i=0; i<10; i++)
    {
    }
}
 
int main()
{
    /* int clock_gettime( clockid_t clock_id, struct
     timespec *tp ); The clock_gettime() function gets
     the current time of the clock specified by clock_id,
     and puts it into the buffer  pointed to by tp.tp
     parameter points to a structure containing
     atleast the following members:   
     struct timespec {
               time_t   tv_sec;        // seconds
               long     tv_nsec;       // nanoseconds
           };
    clock id = CLOCK_REALTIME, CLOCK_PROCESS_CPUTIME_ID,
               CLOCK_MONOTONIC ...etc
    CLOCK_REALTIME : clock  that  measures real (i.e., wall-clock) time.
    CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer
                               from the CPU.
    CLOCK_MONOTONIC : High resolution timer that is unaffected
                      by system date changes (e.g. NTP daemons).  */
    struct timespec start, end;
 
    // start timer.
    // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
    // clock_gettime(CLOCK_REALTIME, &start);
    clock_gettime(CLOCK_MONOTONIC, &start);
 
    // unsync the I/O of C and C++.
    ios_base::sync_with_stdio(false);
 
    fun();
 
    // stop timer.
    // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end);
    // clock_gettime(CLOCK_REALTIME, &end);
    clock_gettime(CLOCK_MONOTONIC, &end);
 
    // Calculating total time taken by the program.
    double time_taken;
    time_taken = (end.tv_sec - start.tv_sec) * 1e9;
    time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9;
 
    cout << "Time taken by program is : " << fixed
         << time_taken << setprecision(9);
    cout << " sec" << endl;
    return 0;
}


Output:

Time taken by program is : 0.000028 sec
  1. Using chrono::high_resolution_clock in C++.

chrono : Chrono library is used to deal with date and time. This library was designed to deal with the fact that timers and clocks might be different on different systems and thus to improve over time in terms of precision.chrono is the name of a header, but also of a sub-namespace, All the elements in this header are not defined directly under the std namespace (like most of the standard library) but under the std::chrono namespace.

  1. Below program to demonstrate how to measure execution time using high_resolution_clock function. For detail info on chrono library see this and this 

CPP




#include <bits/stdc++.h>
#include <chrono>
using namespace std;
 
 
// A sample function whose time taken to
// be measured
void fun()
{
    for (int i=0; i<10; i++)
    {
    }
}
 
int main()
{
    auto start = chrono::high_resolution_clock::now();
 
    // unsync the I/O of C and C++.
    ios_base::sync_with_stdio(false);
 
    fun();
 
    auto end = chrono::high_resolution_clock::now();
 
    // Calculating total time taken by the program.
    double time_taken =
      chrono::duration_cast<chrono::nanoseconds>(end - start).count();
 
    time_taken *= 1e-9;
 
    cout << "Time taken by program is : " << fixed
         << time_taken << setprecision(9);
    cout << " sec" << endl;
    return 0;
}


Output:

Time taken by program is : 0.000024 sec

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments