今天在用Rstudio运行一段示例代码的时候,看到有profiling的功能。随手记录一下。
从这功能名来看就是可以剖析代码性能的。所以就点了下start profiling。
第一次点的时候,会下截相应的功能包,这个功能是Profvis包提供的。
官方的Overview介绍如下:
Profvis is a tool for helping you to understand how R spends its time. It provides a interactive graphical interface for visualizing data from Rprof
, R’s built-in tool for collecting profiling data.
Most R users have had times where we’ve wanted our code to run faster. However, it’s not always clear how to accomplish this. A common approach is to rely on intuition, and on wisdom from the broader R community about speeding up R code. One drawback to this is it can lead to a focus on optimizing things that actually take a small proportion of the overall running time.
Suppose you make a loop run 5 times faster. That sounds like a huge improvement, but if that loop only takes 10% of the total time, it’s still only a 8% speedup overall. Another drawback is that, although many of the commonly-held beliefs are true (for example, preallocating memory can speed things up), some are not (e.g., that *apply
functions are inherently faster than for
loops). This can lead us to spend time doing “optimizations” that don’t really help. To make slow code faster, we need accurate information about what is making our code slow.
在console窗口上就会出现这个显示:
显示当前正在profiling代码的状态。然后运行一下示例代码,之后点击Stop Profiling。会生成一个profile的文件。
查看下生成的Profile文件。
下半部分是火焰图,上半部分是代码区。点击相应的代码,会高亮显示火焰图中的位置。同样,点击相应的火焰图也会显示到具体的某一行代码。双击代码行可以直接定位到源代码的对应行。
点击Data,可以看到图状结构的内存和时间的消耗。
总结一下,
这样的工具在不同的语言中都有相应的工具,像在java中有jprofiler/jvirtualVM之为类的,还有一些diagnostics工具都可以做得到,现在的APM也是用这样的手段来监控到代码层(如果APM能监控到代码层的话)。
C/C++应用可用的工具就更多了,不仅有之前写过的valgrind,还有系统调试工具perf/systemtap也有部分相通的部分。有兴趣的可以看下之前的文章。
《性能工具之内核调试工具》
《性能工具之代码级剖析工具》
《性能分析之valgrind及相关工具》
再多啰嗦一句,工具是让人工作更快的,但是原理是一定要理解的。