转载于:https://shaojun.name/2016/07/260
btrace script
import static com.sun.btrace.BTraceUtils.name;
import static com.sun.btrace.BTraceUtils.print;
import static com.sun.btrace.BTraceUtils.println;
import static com.sun.btrace.BTraceUtils.probeClass;
import static com.sun.btrace.BTraceUtils.probeMethod;
import static com.sun.btrace.BTraceUtils.str;
import static com.sun.btrace.BTraceUtils.strcat;
import static com.sun.btrace.BTraceUtils.timeMillis; import com.sun.btrace.annotations.BTrace;
import com.sun.btrace.annotations.Kind;
import com.sun.btrace.annotations.Location;
import com.sun.btrace.annotations.OnMethod;
import com.sun.btrace.annotations.TLS; @BTrace
public class MethodTimeCost { @TLS private static long starttime; @OnMethod(clazz="/org\\..*/", method="/.+/",location=@Location(Kind.ENTRY))
public static void startExecute() {
starttime = timeMillis();
} @OnMethod(clazz="/org\\..*/", method="/.+/",location=@Location(Kind.RETURN))
public static void endExecute() {
long timecost = timeMillis() - starttime;
if(timecost > 50) {
print(strcat(strcat(name(probeClass()), "."), probeMethod()));
print(" [");
print(strcat("Time taken : ", str(timecost)));
println("]");
}
}
}
被测试代码:
package org.shaojun.test; public class MyTest { public static void main(String[] args) { for(int i = 0;i < 100; i++) {
Thread t = new Thread() {
@Override
public void run() {
Slow slow = new Slow();
slow.query();
}
};
t.start();
}
}
} package org.shaojun.test; public class Slow { public void query() {
while(true) {
slow();
}
} public void slow() {
slow2();
} public void slow2() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("helloworld");
}
}
执行以下代码:
/btrace -cp build 2042 /Users/shaojun/Documents/workspace/btrace/src/MethodTimeCost.java
其中,2042是被测试代码的java进程id
/Users/shaojun/Documents/workspace/btrace/src/MethodTimeCost.java是btrace脚本所在位置
-cp build可以沿用
以下是btrace下载地址:
btrace-bin-1.3.7