C++ Time measurement of functions

随声附和 提交于 2019-12-08 06:24:05

问题


I need to measure the time of a C++ programs, especially the overall running time of some recursive functions. There are a lot of function calls inside other functions. My first thought was to implement some time measurements functions in the actual code.

The problem with gprof is, that it prints out the time of class operators of a datatype, but i only need the infomartion about the functions and "-f func_name prog_name" wont work.

So, what is the most common way in science to measure time of a numerical program?

Its something like this:

function2()
{
}
function1()
{
  function2();
  funtcion1();
}
int main(){
function1();
}

回答1:


If you're using the GNU package, i.e. gcc, you can try gprof. Just compile your program with -g and -pg flags and then run gprof <your_program_name>

gprof: http://www.cs.utah.edu/dept/old/texinfo/as/gprof_toc.html

EDIT: In order to increase the level of detail you can run gprof with other flags:

-l (--line) enables line by line profiling, giving you a histogram hits to be charged to individual lines of code, instead of functions.

-a Don’t include private functions in the output.

-e <function> Exclude output for a function <function>. Use this when there are functions that won’t be changed. For example, some sites have source code that’s been approved by a regulatory agency, and no matter how inefficient, the code will remain unchanged.

-E <function> Also exclude the time spent in the function from the percentage tables.

-f <function> The opposite of -e: only track time in <function>.

-F <function> Only use the time in <function> when calculating percentages.

-b Don’t print the explanatory text. If you’re more experienced, you can appreciate this option.

-s Accumulate samples. By running the program several times, it’s possible to get a better picture of where time is spent. For example, a slow routine may not be called for all input values, and therefore you maybe mislead reading where to find performance problems.




回答2:


If you need higher precision (for functions which do not take more than few (or less) milliseconds), you can use std::chrono::high_resolution_clock:

auto beginT = std::chrono::high_resolution_clock::now();
//Your computation here
auto endT = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(endT - beginT).count()

The std::chrono::high_resolution_clock can be found in chrono header and is part of C++11 stadard.



来源:https://stackoverflow.com/questions/19479383/c-time-measurement-of-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!