Linux程序优化实践

针对监控系统--核心组件做优化时总结的,不局限于性能优化,权且做个记录吧。
1.为何要优化
欲对某个程序做优化,首先要弄清楚需要优化的原因,常见的原因包括:
功能有欠缺
性能有欠缺
存在安全隐患
维护开销大


此次优化的主要原因:
该组件做报警数据分析效率低下,不能满足大批量的报警并发情况
当前版本存有较多安全隐患


2.分析程序
  分析程序的手段很多,通常情况下可以借助工具分析程序的call graph帮助理清程序逻辑,使用profile工具找出性能瓶颈。当然,终结做法还得rtfc。
2.1 call graph
call graph以图的方式很直观地反应出函数的调用关系,帮助理清程序逻辑。
常用工具:doxygen egypt gprof等
参考:http://en.wikipedia.org/wiki/Call_graph


Egypt:
Egypt is a devilishly simple tool for creating call graphs of C programs.
http://www.gson.org/egypt/
http://www.gson.org/egypt/egypt.html
勘误:make CFLAGS=-dr 应为make CFLAGS=-dx -fdump-rtl-expand


Doxygen:
Doxygen is a tool for writing software reference documentation.
快速指南:http://www-scf.usc.edu/~peterchd/doxygen/


2.2 profile分析性能
  Profiling, a form of dynamic program analysis (as opposed to static code analysis), is the investigation of a program’s behavior using information gathered as the program executes.
http://en.wikipedia.org/wiki/Software_performance_analysis#Instrumentation
gprof:
GNU工具之一,编译时在每个函数的出入口加入profiling的代码,运行时统计程序在用户态的执行信息。
可以得到每个函数的调用次数,执行时间,调用关系等信息,适合查找用户级程序的性能瓶颈,不适合分析很多时间都在内核态执行的程序。
http://sourceware.org/binutils/docs/gprof/
使用方式:
make CFLAGS = pg LDFLAGS = pg
运行程序./program_name
分析结果:gprof program_name gmon.out
注意事项:
必须在编译和链接的时候都使用-pg选项
如果想跟踪到使用的库,连接时必须使用-lcp库
程序不能是守护进程
程序必需正常退出,返回操作系统


oprof:
使用硬件调试寄存器来统计信息,进行profiling的开销比较小,而且可以对内核进行profiling。
可以得到gprof得不到的cache的缺失率,memory的访存信息,分支预测错误率等等,但得不到函数调用次数。
http://oprofile.sourceforge.net/about/
使用:
opcontrol –reset
opcontrol –init
opcontrol –setup –separate=lib,kernel,thread –no-vmlinux
opcontrol –start-daemon
opcontrol –start
opcontrol –dump
opcontrol –stop
opreport –demangle=smart –symbols –long-filenames –merge
tgid /usr/local/wsms al/bin/al
注意事项:
待分析程序必须带有符号信息,可以用nm命令判断。
安装debuginfo包可以使oprofile获得程序的符号信息。


2.3 rtfc
工具提供一种帮助,真正找出问题的解决方案还得rtfc,rtfc是一种精神。

原文地址:https://www.cnblogs.com/OrcinusOrca/p/14816527.html