Search code examples
cexecution-time

Getting 0 when trying to measure the execution time of function in C


I have simple function which takes random words and puts them in lexicographical order using insertion sort algorithm.I have no problem with function(It works,tested),but when i try to measure execution time of function using two different clock() values, i get same values before and after the execution of function,so it shows 0 as elapsed time

                clock_t t1 = clock();
                InsertionSort(data, n);
                clock_t t2 = clock();

                /*
                * Display the results.
                */

                for (size = i, i = 0; i < size; ++i)
                {
                    printf("data[%d] = \"%s\"\n", (int)i, data[i]);
                }

                /*
                * Display the execution time
                */
                printf("The time taken is.. %g ", (t2 -t1));

Solution

  • The time difference is too small to be measured by this method, without adding more code to execute. – Weather Vane

    Usually, you contrive a way to measure a large number of loops of what you want to time. 10, 100, 1000, whatever produces a significant result. Bear in mind too that on a multi-tasking OS each iteration will take a slightly different time, and so you'll also establish a typical average.The result might also be affected by processor caching and/or file caching. – Weather Vane