Find time it takes for a C++ function to run

This question already has an answer here:

  • How can I profile C++ code running in Linux? 10 answers
  • Measuring execution time of a function in C++ 4 answers

  • There's another way to find the problem(s) than by getting a breakdown of function times.

    Run it under a debugger, and manually interrupt it several times, and each time examine the call stack. If you look at each level of the call stack that's in your code, you can see exactly why that moment in time is being spent.

    Suppose you have a speed problem that, when fixed, will save some fraction of time, like 30%. That means each stack sample that you examine has at least a 30% chance of happening during the problem. So, turning it around, if you see it doing something that could be eliminated, and you see it on more than one sample, you've found your problem! (or at least one of them) **

    That's the random-pausing technique. It will find any problem that timers will, and problems that they won't.

    ** You might have to think about it a bit. If you see it doing something on a single sample, that doesn't mean much. Even if the code is only doing a thousand completely different things, none of them taking significant time, it has to stop somewhere. But if you see it doing something, and you see it on more than one sample, and you haven't taken a lot of samples, the probability that you would hit the same insignificant thing twice is very very small. So it is far more likely that its probability is significant. In fact, a reasonable guess of its probability is the number of samples in which you saw it, divided by the total number of samples.


    You can create your own timer class. At the starting of each block call method to reset the timer variable to zero and get the timer at the end of the code block. You can do this in various blocks of the code. Once you had identified the code block that takes more time, you can have internal timers too.. If you want try a standard tool than I would recommend to use gprof. http://www.thegeekstuff.com/2012/08/gprof-tutorial/


    #include <iostream> 
    #include <ctime>
    
    int main() {
        std::clock_t start = std::clock();
    
        //code here
    
        double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
        std::cout << duration << std::endl;
    }
    
    链接地址: http://www.djcxy.com/p/40358.html

    上一篇: DateTime.Now是衡量函数性能的最佳方法吗?

    下一篇: 找出C ++函数运行所需的时间