1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.christianschenk.aspectj.profiling;
20
21 import java.util.HashMap;
22 import java.util.Map;
23
24 import org.apache.log4j.Logger;
25 import org.aspectj.lang.JoinPoint;
26 import org.aspectj.lang.ProceedingJoinPoint;
27 import org.aspectj.lang.annotation.After;
28 import org.aspectj.lang.annotation.Around;
29 import org.aspectj.lang.annotation.Aspect;
30 import org.aspectj.lang.annotation.Pointcut;
31
32
33
34
35
36
37
38
39 @Aspect
40 public abstract class AbstractProfilingAspect {
41
42 private static final Logger log = Logger.getLogger("profiling");
43
44 private final Map<String, Long> methodTimes;
45
46 private final String topLevelMethod;
47
48 public AbstractProfilingAspect(final String topLevelMethod) {
49 this.methodTimes = new HashMap<String, Long>();
50 this.topLevelMethod = topLevelMethod;
51 }
52
53
54
55
56 @Pointcut
57 protected abstract void profile();
58
59
60
61
62
63 @Around("profile()")
64 public void aroundProfileMethods(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
65 final long start, end;
66 start = System.nanoTime();
67 thisJoinPoint.proceed();
68 end = System.nanoTime();
69 this.methodTimes.put(this.getJoinPointName(thisJoinPoint), ((end - start) / 1000) / 1000);
70 }
71
72
73
74
75 @After("profile()")
76 public void afterTopLevelMethod(final JoinPoint joinPoint) {
77 if (this.topLevelMethod.equals(this.getJoinPointName(joinPoint)) == false) return;
78
79 final long overallTime = this.methodTimes.get(this.topLevelMethod);
80 log.debug("Results for " + this.topLevelMethod + " (" + overallTime + "ms)");
81 for (final String method : this.methodTimes.keySet()) {
82 if (method.equals(this.topLevelMethod)) continue;
83 final long methodTime = this.methodTimes.get(method);
84 final double percent = Math.round(((double) methodTime / (double) overallTime) * 100);
85 log.debug("Method: " + method + "() took " + methodTime + "ms (" + percent + "%)");
86 }
87 }
88
89
90
91
92
93 private final String getJoinPointName(final JoinPoint joinPoint) {
94 return joinPoint.getThis().getClass().getSimpleName() + "." + joinPoint.getSignature().getName();
95 }
96 }