001    package org.shiftone.jrat.core.jmx.benchmark;
002    
003    
004    import org.shiftone.jrat.core.HandlerFactory;
005    import org.shiftone.jrat.core.spi.MethodHandler;
006    import org.shiftone.jrat.util.log.Logger;
007    import org.shiftone.jrat.util.time.Clock;
008    
009    
010    /**
011     * @author jeff@shiftone.org (Jeff Drost)
012     */
013    public class Benchmark implements BenchmarkMBean {
014    
015        private static final Logger LOG = Logger.getLogger(Benchmark.class);
016        private MethodHandler methodHandler;
017        private long iterations = 1000000;
018    
019        private void doWork() {
020            ;
021        }
022    
023    
024        public void monitorDoWork() {
025    
026            methodHandler.onMethodStart(this);
027    
028            long start = Clock.currentTimeMillis();
029    
030            doWork();
031            methodHandler.onMethodFinish(this, Clock.currentTimeMillis() - start, null);
032        }
033    
034    
035        public long getIterations() {
036            return iterations;
037        }
038    
039    
040        public void setIterations(long iterations) {
041            this.iterations = iterations;
042        }
043    
044    
045        public String calculateCostPerMethodCallNanosText() {
046            return "JRat is adding an overhead of about " + calculateCostPerMethodCallNanos()
047                    + " nanoseconds to each instrumented method call.";
048        }
049    
050    
051        public double calculateCostPerMethodCallNanos() {
052    
053            methodHandler = HandlerFactory.getMethodHandler(Benchmark.class, "doWork", "()V");
054    
055            long start;
056    
057            start = Clock.currentTimeMillis();
058    
059            for (int i = 0; i < iterations; i++) {
060                doWork();
061            }
062    
063            long raw = Clock.currentTimeMillis() - start;
064    
065            start = Clock.currentTimeMillis();
066    
067            for (int i = 0; i < iterations; i++) {
068                monitorDoWork();
069            }
070    
071            long jrat = Clock.currentTimeMillis() - start;
072            long delta = jrat - raw;
073            double each = (double) delta / (double) iterations;
074    
075            LOG.info("overhead = " + each + " nanoseconds");
076    
077            return each;
078        }
079    }