Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How can I find the calculation time in nanosecond in C?

+3 votes
asked Sep 25, 2020 by Dark Phoenix (150 points)
#include <stdio.h>
#include <time.h>

int main()
{
    int i,j,vertex=100;
    double cal;
    clock_t start, end;
    start = clock();

    for(i=0; i<vertex; i++)
    {
        for(j=0; j<vertex; j++)
        {
            i=i+j;
        }
    }

    for(j=0; j<vertex; j++)
    {
        for(i=0; i<vertex; i++)
        {
            i=i+j;
        }
    }
    end = clock();
    cal = (end-start)/CLOCKS_PER_SEC;

    printf("%.20lf",cal);
    return 0;
}

1 Answer

0 votes
answered Sep 27, 2020 by xDELLx (10,520 points)

Source: https://stackoverflow.com/questions/12722904/how-to-use-struct-timeval-to-get-the-execution-time

Corrected program below:

#include <stdio.h>
#include <time.h>
#include <sys/time.h> // for struct timeval
int main()
{
    int i,j,vertex=100;
    double cal;
    clock_t start, end;
    struct timeval tvalBefore, tvalAfter;
    gettimeofday (&tvalBefore, NULL);
    start = clock();

    for(i=0; i<vertex; i++)
    {
        for(j=0; j<vertex; j++)
        {
            i=i+j;
        }
    }

    for(j=0; j<vertex; j++)
    {
        for(i=0; i<vertex; i++)
        {
            i=i+j;
        }
    }
    end = clock();
    //sleep(1);
    gettimeofday (&tvalAfter, NULL);
    cal = (end-start)/CLOCKS_PER_SEC;

    printf("%.20lf",cal);
    printf("\nTime in microseconds: %ld microseconds\n",
            ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
           +tvalAfter.tv_usec) - tvalBefore.tv_usec
          ); // Added semicolon
    return 0;
}

Please refer man pages (if on linux ) or google the function calls & you will get enough data t o make sense of them.

C++ has a nano second clock, not sure about it in C.Some third party libs can give nano second precision, but even achieving computing times of micro seconds is a tremendous effort .

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...