Measure time taken by a function in C got always 0.000000How to measure time in milliseconds using ANSI C?Measuring time taken by an exec()-ed process on linuxEasily measure elapsed timeMeasuring time taken by a function: clock_gettimeScanf always returning 0.000000Measuring average time taken for context switchThis C function should always return false, but it doesn’tLinker error: /usr/bin/ld: cannot find -lcWhy does the time for this simple program to run double if run quickly in succession?Float function always returning 0.000000

Contour plot of a sequence of spheres with increasing radius

Remove outer padding in tikzcd

Complex conjugate and transpose "with respect to a basis"

How should Thaumaturgy's "three times as loud as normal" be interpreted?

Is mountain bike good for long distances?

What's the biggest difference between these two photos?

Did "Dirty Harry" feel lucky?

How can Schrödinger's cat be both dead and alive?

How do we create our own symbolisms?

How can I hint that my character isn't real?

Is there a "right" way to interpret a novel, if not, how do we make sure our novel is interpreted correctly?

How do Scrum teams manage their dependencies on other teams?

How can faith be maintained in a world of living gods?

How can I sync Mac Calendar with my own server?

Was Robin Hood's point of view ethically sound?

Why do the British opposition parties not want a new election?

Why is it that I have to play this note on the piano as A sharp?

Capacitors with same voltage, same capacitance, same temp, different diameter?

The pirate treasure of Leatherback Atoll

Is there a specific way to describe over-grown, old, tough vegetables?

What is the purpose of the rotating plate in front of the lock?

How can I finish my PhD?

Supervisor wants me to support a diploma-thesis software tool after I graduated

What makes things real?



Measure time taken by a function in C got always 0.000000


How to measure time in milliseconds using ANSI C?Measuring time taken by an exec()-ed process on linuxEasily measure elapsed timeMeasuring time taken by a function: clock_gettimeScanf always returning 0.000000Measuring average time taken for context switchThis C function should always return false, but it doesn’tLinker error: /usr/bin/ld: cannot find -lcWhy does the time for this simple program to run double if run quickly in succession?Float function always returning 0.000000






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I read an article form geeksforgeeks.The code shows a funciton to measure the time function cost.



In my machine ,I always got 0.000000 no matter how long I press enter.



I print t = clock() - t; t always equal to 0.00000,I rewrite the statement to this,still got 0.000000.



clock_t m;
m = clock() - t;


gcc version in centos7



[root@localhost log]# gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-28)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


/* Program to demonstrate time taken by function fun() */
#include <stdio.h>
#include <time.h>

// A function that terminates when enter key is pressed
void fun()

printf("fun() starts n");
printf("Press enter to stop fun n");
while(1)

if (getchar())
break;

printf("fun() ends n");


// The main program calls fun() and measures time taken by fun()
int main()

// Calculate the time taken by fun()
clock_t t;
t = clock();
fun();
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds

printf("fun() took %f seconds to execute n", time_taken);
return 0;











share|improve this question



















  • 2





    Your code works fine here. Did you try to investigate this? Did you try to printf the intermediate values and variables involved?

    – Jabberwocky
    Mar 28 at 7:34







  • 1





    If clock() happens to return "number of 100 millisecond ticks", then (if you're unlucky) the function could take 99.99 milliseconds and it'd end up truncated to zero.

    – Brendan
    Mar 28 at 7:35






  • 3





    clock() returns CPU time (of which you probably aren't using much), not wall clocks. use time() instead (or make the loop break on getchar() == 'a' or similar and feed it a bunch of newlines before 'a').

    – Hasturkun
    Mar 28 at 7:36












  • Hrm - could change it to printf("fun() took between %f and %f seconds to execute n", time_taken - 1.0/CLOCKS_PER_SEC, time_taken + 1.0/CLOCKS_PER_SEC); . That'd give you a better idea of how precise your clock() is.

    – Brendan
    Mar 28 at 7:39







  • 1





    I'll also point out the reason you aren't using much CPU time is that getchar() is blocking. You can also use clock_gettime() (or gettimeofday()) for more accurate wall clocks, if that's what you're after.

    – Hasturkun
    Mar 28 at 7:43


















0















I read an article form geeksforgeeks.The code shows a funciton to measure the time function cost.



In my machine ,I always got 0.000000 no matter how long I press enter.



I print t = clock() - t; t always equal to 0.00000,I rewrite the statement to this,still got 0.000000.



clock_t m;
m = clock() - t;


gcc version in centos7



[root@localhost log]# gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-28)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


/* Program to demonstrate time taken by function fun() */
#include <stdio.h>
#include <time.h>

// A function that terminates when enter key is pressed
void fun()

printf("fun() starts n");
printf("Press enter to stop fun n");
while(1)

if (getchar())
break;

printf("fun() ends n");


// The main program calls fun() and measures time taken by fun()
int main()

// Calculate the time taken by fun()
clock_t t;
t = clock();
fun();
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds

printf("fun() took %f seconds to execute n", time_taken);
return 0;











share|improve this question



















  • 2





    Your code works fine here. Did you try to investigate this? Did you try to printf the intermediate values and variables involved?

    – Jabberwocky
    Mar 28 at 7:34







  • 1





    If clock() happens to return "number of 100 millisecond ticks", then (if you're unlucky) the function could take 99.99 milliseconds and it'd end up truncated to zero.

    – Brendan
    Mar 28 at 7:35






  • 3





    clock() returns CPU time (of which you probably aren't using much), not wall clocks. use time() instead (or make the loop break on getchar() == 'a' or similar and feed it a bunch of newlines before 'a').

    – Hasturkun
    Mar 28 at 7:36












  • Hrm - could change it to printf("fun() took between %f and %f seconds to execute n", time_taken - 1.0/CLOCKS_PER_SEC, time_taken + 1.0/CLOCKS_PER_SEC); . That'd give you a better idea of how precise your clock() is.

    – Brendan
    Mar 28 at 7:39







  • 1





    I'll also point out the reason you aren't using much CPU time is that getchar() is blocking. You can also use clock_gettime() (or gettimeofday()) for more accurate wall clocks, if that's what you're after.

    – Hasturkun
    Mar 28 at 7:43














0












0








0








I read an article form geeksforgeeks.The code shows a funciton to measure the time function cost.



In my machine ,I always got 0.000000 no matter how long I press enter.



I print t = clock() - t; t always equal to 0.00000,I rewrite the statement to this,still got 0.000000.



clock_t m;
m = clock() - t;


gcc version in centos7



[root@localhost log]# gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-28)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


/* Program to demonstrate time taken by function fun() */
#include <stdio.h>
#include <time.h>

// A function that terminates when enter key is pressed
void fun()

printf("fun() starts n");
printf("Press enter to stop fun n");
while(1)

if (getchar())
break;

printf("fun() ends n");


// The main program calls fun() and measures time taken by fun()
int main()

// Calculate the time taken by fun()
clock_t t;
t = clock();
fun();
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds

printf("fun() took %f seconds to execute n", time_taken);
return 0;











share|improve this question














I read an article form geeksforgeeks.The code shows a funciton to measure the time function cost.



In my machine ,I always got 0.000000 no matter how long I press enter.



I print t = clock() - t; t always equal to 0.00000,I rewrite the statement to this,still got 0.000000.



clock_t m;
m = clock() - t;


gcc version in centos7



[root@localhost log]# gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-28)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


/* Program to demonstrate time taken by function fun() */
#include <stdio.h>
#include <time.h>

// A function that terminates when enter key is pressed
void fun()

printf("fun() starts n");
printf("Press enter to stop fun n");
while(1)

if (getchar())
break;

printf("fun() ends n");


// The main program calls fun() and measures time taken by fun()
int main()

// Calculate the time taken by fun()
clock_t t;
t = clock();
fun();
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds

printf("fun() took %f seconds to execute n", time_taken);
return 0;








c






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 28 at 7:29









J.DoeJ.Doe

796 bronze badges




796 bronze badges










  • 2





    Your code works fine here. Did you try to investigate this? Did you try to printf the intermediate values and variables involved?

    – Jabberwocky
    Mar 28 at 7:34







  • 1





    If clock() happens to return "number of 100 millisecond ticks", then (if you're unlucky) the function could take 99.99 milliseconds and it'd end up truncated to zero.

    – Brendan
    Mar 28 at 7:35






  • 3





    clock() returns CPU time (of which you probably aren't using much), not wall clocks. use time() instead (or make the loop break on getchar() == 'a' or similar and feed it a bunch of newlines before 'a').

    – Hasturkun
    Mar 28 at 7:36












  • Hrm - could change it to printf("fun() took between %f and %f seconds to execute n", time_taken - 1.0/CLOCKS_PER_SEC, time_taken + 1.0/CLOCKS_PER_SEC); . That'd give you a better idea of how precise your clock() is.

    – Brendan
    Mar 28 at 7:39







  • 1





    I'll also point out the reason you aren't using much CPU time is that getchar() is blocking. You can also use clock_gettime() (or gettimeofday()) for more accurate wall clocks, if that's what you're after.

    – Hasturkun
    Mar 28 at 7:43













  • 2





    Your code works fine here. Did you try to investigate this? Did you try to printf the intermediate values and variables involved?

    – Jabberwocky
    Mar 28 at 7:34







  • 1





    If clock() happens to return "number of 100 millisecond ticks", then (if you're unlucky) the function could take 99.99 milliseconds and it'd end up truncated to zero.

    – Brendan
    Mar 28 at 7:35






  • 3





    clock() returns CPU time (of which you probably aren't using much), not wall clocks. use time() instead (or make the loop break on getchar() == 'a' or similar and feed it a bunch of newlines before 'a').

    – Hasturkun
    Mar 28 at 7:36












  • Hrm - could change it to printf("fun() took between %f and %f seconds to execute n", time_taken - 1.0/CLOCKS_PER_SEC, time_taken + 1.0/CLOCKS_PER_SEC); . That'd give you a better idea of how precise your clock() is.

    – Brendan
    Mar 28 at 7:39







  • 1





    I'll also point out the reason you aren't using much CPU time is that getchar() is blocking. You can also use clock_gettime() (or gettimeofday()) for more accurate wall clocks, if that's what you're after.

    – Hasturkun
    Mar 28 at 7:43








2




2





Your code works fine here. Did you try to investigate this? Did you try to printf the intermediate values and variables involved?

– Jabberwocky
Mar 28 at 7:34






Your code works fine here. Did you try to investigate this? Did you try to printf the intermediate values and variables involved?

– Jabberwocky
Mar 28 at 7:34





1




1





If clock() happens to return "number of 100 millisecond ticks", then (if you're unlucky) the function could take 99.99 milliseconds and it'd end up truncated to zero.

– Brendan
Mar 28 at 7:35





If clock() happens to return "number of 100 millisecond ticks", then (if you're unlucky) the function could take 99.99 milliseconds and it'd end up truncated to zero.

– Brendan
Mar 28 at 7:35




3




3





clock() returns CPU time (of which you probably aren't using much), not wall clocks. use time() instead (or make the loop break on getchar() == 'a' or similar and feed it a bunch of newlines before 'a').

– Hasturkun
Mar 28 at 7:36






clock() returns CPU time (of which you probably aren't using much), not wall clocks. use time() instead (or make the loop break on getchar() == 'a' or similar and feed it a bunch of newlines before 'a').

– Hasturkun
Mar 28 at 7:36














Hrm - could change it to printf("fun() took between %f and %f seconds to execute n", time_taken - 1.0/CLOCKS_PER_SEC, time_taken + 1.0/CLOCKS_PER_SEC); . That'd give you a better idea of how precise your clock() is.

– Brendan
Mar 28 at 7:39






Hrm - could change it to printf("fun() took between %f and %f seconds to execute n", time_taken - 1.0/CLOCKS_PER_SEC, time_taken + 1.0/CLOCKS_PER_SEC); . That'd give you a better idea of how precise your clock() is.

– Brendan
Mar 28 at 7:39





1




1





I'll also point out the reason you aren't using much CPU time is that getchar() is blocking. You can also use clock_gettime() (or gettimeofday()) for more accurate wall clocks, if that's what you're after.

– Hasturkun
Mar 28 at 7:43






I'll also point out the reason you aren't using much CPU time is that getchar() is blocking. You can also use clock_gettime() (or gettimeofday()) for more accurate wall clocks, if that's what you're after.

– Hasturkun
Mar 28 at 7:43













3 Answers
3






active

oldest

votes


















0
















Hello try this instead:



unsigned int t=time(0);
fun();
unsigned int result=time(0)-t; // result is the time taken by fun





share|improve this answer
































    0
















    In case you're trying to measure "CPU time used" (and not "wall clock time spent waiting for user to press a key"), then...



    Imagine if the OS has a timer that generates an IRQ 10 times per second, and the IRQ handler just does ticks++; and clock() is just return ticks;. In this case, CLOCKS_PER_SEC would be 10.



    Now, if you call clock() once just before the timer IRQ occurs and again immediately after the timer IRQ occurs, the difference between the values returned might be 1 (equal to 100 ms) even significantly less time passed between calls to clock().



    Alternatively; if you call clock() once immediately after the timer IRQ occurs and again just before the timer IRQ occurs again, the difference between the values returned might be 0, even significantly more time passed between calls to clock().



    Essentially, the difference between values returned by clock() is "up to 1/CLOCKS_PER_SEC sooner than you think" and "up to 1/CLOCKS_PER_SEC longer than you think".



    Note that the value of CLOCKS_PER_SEC is implementation defined. Depending on various things (which version of which OS running on which hardware, with which C library) CLOCKS_PER_SEC can be anything, and could be as low as 10 and could be as high has 4 billion.






    share|improve this answer
































      0
















      clock() measures the CPU time, that is the time that the processor has been active. You may want to measure wall clock time instead, which is the number of seconds from the start to the end of the function run:



      struct timeval start;
      gettimeofday(&start, 0);
      fun();
      struct timeval end;
      gettimeofday(&end, 0);
      double time_taken = (end.tv_sec - start.tv_sec)
      + (end.tv_usec - start.tv_usec)*1e-6;


      To make this work, you must also include <sys/time.h>






      share|improve this answer





























        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );














        draft saved

        draft discarded
















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55392224%2fmeasure-time-taken-by-a-function-in-c-got-always-0-000000%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0
















        Hello try this instead:



        unsigned int t=time(0);
        fun();
        unsigned int result=time(0)-t; // result is the time taken by fun





        share|improve this answer





























          0
















          Hello try this instead:



          unsigned int t=time(0);
          fun();
          unsigned int result=time(0)-t; // result is the time taken by fun





          share|improve this answer



























            0














            0










            0









            Hello try this instead:



            unsigned int t=time(0);
            fun();
            unsigned int result=time(0)-t; // result is the time taken by fun





            share|improve this answer













            Hello try this instead:



            unsigned int t=time(0);
            fun();
            unsigned int result=time(0)-t; // result is the time taken by fun






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 28 at 7:41









            M.IsmailM.Ismail

            17910 bronze badges




            17910 bronze badges


























                0
















                In case you're trying to measure "CPU time used" (and not "wall clock time spent waiting for user to press a key"), then...



                Imagine if the OS has a timer that generates an IRQ 10 times per second, and the IRQ handler just does ticks++; and clock() is just return ticks;. In this case, CLOCKS_PER_SEC would be 10.



                Now, if you call clock() once just before the timer IRQ occurs and again immediately after the timer IRQ occurs, the difference between the values returned might be 1 (equal to 100 ms) even significantly less time passed between calls to clock().



                Alternatively; if you call clock() once immediately after the timer IRQ occurs and again just before the timer IRQ occurs again, the difference between the values returned might be 0, even significantly more time passed between calls to clock().



                Essentially, the difference between values returned by clock() is "up to 1/CLOCKS_PER_SEC sooner than you think" and "up to 1/CLOCKS_PER_SEC longer than you think".



                Note that the value of CLOCKS_PER_SEC is implementation defined. Depending on various things (which version of which OS running on which hardware, with which C library) CLOCKS_PER_SEC can be anything, and could be as low as 10 and could be as high has 4 billion.






                share|improve this answer





























                  0
















                  In case you're trying to measure "CPU time used" (and not "wall clock time spent waiting for user to press a key"), then...



                  Imagine if the OS has a timer that generates an IRQ 10 times per second, and the IRQ handler just does ticks++; and clock() is just return ticks;. In this case, CLOCKS_PER_SEC would be 10.



                  Now, if you call clock() once just before the timer IRQ occurs and again immediately after the timer IRQ occurs, the difference between the values returned might be 1 (equal to 100 ms) even significantly less time passed between calls to clock().



                  Alternatively; if you call clock() once immediately after the timer IRQ occurs and again just before the timer IRQ occurs again, the difference between the values returned might be 0, even significantly more time passed between calls to clock().



                  Essentially, the difference between values returned by clock() is "up to 1/CLOCKS_PER_SEC sooner than you think" and "up to 1/CLOCKS_PER_SEC longer than you think".



                  Note that the value of CLOCKS_PER_SEC is implementation defined. Depending on various things (which version of which OS running on which hardware, with which C library) CLOCKS_PER_SEC can be anything, and could be as low as 10 and could be as high has 4 billion.






                  share|improve this answer



























                    0














                    0










                    0









                    In case you're trying to measure "CPU time used" (and not "wall clock time spent waiting for user to press a key"), then...



                    Imagine if the OS has a timer that generates an IRQ 10 times per second, and the IRQ handler just does ticks++; and clock() is just return ticks;. In this case, CLOCKS_PER_SEC would be 10.



                    Now, if you call clock() once just before the timer IRQ occurs and again immediately after the timer IRQ occurs, the difference between the values returned might be 1 (equal to 100 ms) even significantly less time passed between calls to clock().



                    Alternatively; if you call clock() once immediately after the timer IRQ occurs and again just before the timer IRQ occurs again, the difference between the values returned might be 0, even significantly more time passed between calls to clock().



                    Essentially, the difference between values returned by clock() is "up to 1/CLOCKS_PER_SEC sooner than you think" and "up to 1/CLOCKS_PER_SEC longer than you think".



                    Note that the value of CLOCKS_PER_SEC is implementation defined. Depending on various things (which version of which OS running on which hardware, with which C library) CLOCKS_PER_SEC can be anything, and could be as low as 10 and could be as high has 4 billion.






                    share|improve this answer













                    In case you're trying to measure "CPU time used" (and not "wall clock time spent waiting for user to press a key"), then...



                    Imagine if the OS has a timer that generates an IRQ 10 times per second, and the IRQ handler just does ticks++; and clock() is just return ticks;. In this case, CLOCKS_PER_SEC would be 10.



                    Now, if you call clock() once just before the timer IRQ occurs and again immediately after the timer IRQ occurs, the difference between the values returned might be 1 (equal to 100 ms) even significantly less time passed between calls to clock().



                    Alternatively; if you call clock() once immediately after the timer IRQ occurs and again just before the timer IRQ occurs again, the difference between the values returned might be 0, even significantly more time passed between calls to clock().



                    Essentially, the difference between values returned by clock() is "up to 1/CLOCKS_PER_SEC sooner than you think" and "up to 1/CLOCKS_PER_SEC longer than you think".



                    Note that the value of CLOCKS_PER_SEC is implementation defined. Depending on various things (which version of which OS running on which hardware, with which C library) CLOCKS_PER_SEC can be anything, and could be as low as 10 and could be as high has 4 billion.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 28 at 7:54









                    BrendanBrendan

                    16.3k17 silver badges36 bronze badges




                    16.3k17 silver badges36 bronze badges
























                        0
















                        clock() measures the CPU time, that is the time that the processor has been active. You may want to measure wall clock time instead, which is the number of seconds from the start to the end of the function run:



                        struct timeval start;
                        gettimeofday(&start, 0);
                        fun();
                        struct timeval end;
                        gettimeofday(&end, 0);
                        double time_taken = (end.tv_sec - start.tv_sec)
                        + (end.tv_usec - start.tv_usec)*1e-6;


                        To make this work, you must also include <sys/time.h>






                        share|improve this answer































                          0
















                          clock() measures the CPU time, that is the time that the processor has been active. You may want to measure wall clock time instead, which is the number of seconds from the start to the end of the function run:



                          struct timeval start;
                          gettimeofday(&start, 0);
                          fun();
                          struct timeval end;
                          gettimeofday(&end, 0);
                          double time_taken = (end.tv_sec - start.tv_sec)
                          + (end.tv_usec - start.tv_usec)*1e-6;


                          To make this work, you must also include <sys/time.h>






                          share|improve this answer





























                            0














                            0










                            0









                            clock() measures the CPU time, that is the time that the processor has been active. You may want to measure wall clock time instead, which is the number of seconds from the start to the end of the function run:



                            struct timeval start;
                            gettimeofday(&start, 0);
                            fun();
                            struct timeval end;
                            gettimeofday(&end, 0);
                            double time_taken = (end.tv_sec - start.tv_sec)
                            + (end.tv_usec - start.tv_usec)*1e-6;


                            To make this work, you must also include <sys/time.h>






                            share|improve this answer















                            clock() measures the CPU time, that is the time that the processor has been active. You may want to measure wall clock time instead, which is the number of seconds from the start to the end of the function run:



                            struct timeval start;
                            gettimeofday(&start, 0);
                            fun();
                            struct timeval end;
                            gettimeofday(&end, 0);
                            double time_taken = (end.tv_sec - start.tv_sec)
                            + (end.tv_usec - start.tv_usec)*1e-6;


                            To make this work, you must also include <sys/time.h>







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Mar 28 at 8:17

























                            answered Mar 28 at 8:10









                            MalinMalin

                            4645 silver badges15 bronze badges




                            4645 silver badges15 bronze badges































                                draft saved

                                draft discarded















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55392224%2fmeasure-time-taken-by-a-function-in-c-got-always-0-000000%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                                155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해