tprofiler初探

1.简介
tprofiler是一个可以在生产环境长期使用的性能分析工具。可以监测每个类,每个方法运行需要多少时间,然后找到性能的瓶颈,这点和jvisualvm这类profiler工具类似。

2.实战
我们准备结合tomcat测一个web应用的性能。这里选取 retwisj来测试。

环境:
Windows7 64bit
JDK 1.7.0_72 64bit
Tomcat 7.0.35
Maven 2.2.1

2.1 首先去git官网将tprofiler的代码clone下来,然后编译
git assembly:assembly

2.2 将TProfiler\pkg\TProfiler\lib\tprofiler-1.0.1.jar复制到apache-tomcat-7.0.35\bin下面,重命名为tprofiler.jar。

2.3 apache-tomcat-7.0.35\bin下面,添加一个文件profile.properties到该目录(文件可以解压jar包找到)

几个参数注意修改:
startProfTime,endProfTime改成测试的时候的时间范围内
logFilePath,methodFilePath,samplerFilePath改对
includePackageStartsWith要注意加入你要监测的类的包名。
我这里改为includePackageStartsWith = org.springframework
但是tprofiler很坑爹,代码里居然把所有org开头的给exclude掉了,所以得改代码
com.taobao.profile.config.ProfFilter
把下面这行注释掉。
//excludePackage.add("org/");

然后改完重新编译打包吧,Σ( ° △ °|||)︴

2.4 apache-tomcat-7.0.35\bin下面,添加一个文件setenv.bat,内容如下
set JAVA_OPTS="-javaagent:tprofiler.jar"


2.5 将retwisj工程clone下来,然后将编译出的retwisj.war放到tomcat的webapp目录下,关于retwisj,可以参考我的另一篇日志 http://xpenxpen.iteye.com/blog/2082966

2.6 启动tomcat

2.7 打开浏览器,http://localhost:8080/retwisj,随便点点

2.8 打开tprofiler客户端,强制刷新查看方法的执行时间
apache-tomcat-7.0.35\bin>java -cp tprofiler.jar com.taobao.profile.client.TProfilerClient 127.0.0.1 50000 flushmethod

2.9 这样就可以看到这个文件了apache-tomcat-7.0.35\bin\logs\tmethod.log
内容大致如下
instrumentclass:1125 instrumentmethod:8228
0 org/springframework/web/SpringServletContainerInitializer:<init>:111
1 org/springframework/web/SpringServletContainerInitializer:onStartup:176


2.10 分析profile日志
apache-tomcat-7.0.35\bin>java -cp tprofiler.jar com.taobao.profile.analysis.ProfilerLogAnalysis logs/tprofiler.log logs/tmethod.log logs/topmethod.log logs/topobject.log
这个命令试下来没用,不知是bug还是什么。我这里不深究了,有tmethod.log也够了。

至此,就可以根据profile日志分析程序的性能瓶颈了。

3.tprofiler原理探究
核心就2个东东:instrument和asm
instrument提供在运行时替换类的字节码的机制,而具体如何编写java字节码则可以用asm或者bcel之类的工具
对于tprofile的源码,稍微看看就行,idea是可以学习借鉴的,但是代码质量,我只能说呵呵吧,大家不要太在意。

4.参考资料
淘宝Tprofiler工具实现分析
Java SE 6 新特性: Instrumentation 新功能
TProfiler部署文档--笔记
Instrumentation: querying the memory usage of a Java object
Measure Java Performance – Sampling or Instrumentation? 本文用aspectj和java instrument结合做profile,看完我对aspectj又有新的认识。原来aspectj也不只是只能在编译期间静态改字节码的,也有和asm一样的运行时动态改字节码的功能。
JIP — The Java Interactive Profiler

猜你喜欢

转载自xpenxpen.iteye.com/blog/2192797