    001    package ifs.util;
    002
    003    /** CPU time measurement. JAVA profiling extension is used.
    004     * Java needs to be executed with -Xrunjprof. When the java is executed outside
    005     * this profiler, {@link System#currentTimeMillis()} is used.
    006     *
    007     * @author <a href="mailto:muller@ktiml.mff.cuni.cz">Tomáš Müller</a>
    008     * @version 1.0
    009     */
    010    public class JProf {
    011        private static boolean sPrecise = true;
    012
    013        /** Current CPU time of this thread in seconds */
    014        public static double currentTimeSec() {
    015            return (sPrecise?((double)getCurrentThreadCpuTime())/1e9:((double)System.currentTimeMillis())/1e3);
    016        }
    017        /** Measurement is based on profiler extension (precise CPU time is returned).
    018         * If false, {@link System#currentTimeMillis()} is used in {@link JProf#currentTimeSec()}.
    019         */
    020        public static boolean isPrecise() { return sPrecise; }
    021
    022        /** Current CPU time of this thread (will fail when jprof is not loaded). Use {@link JProf#currentTimeSec()}.*/
    023        public static native long getCurrentThreadCpuTime();
    024
    025        static {
    026            try {
    027                System.loadLibrary("jprof");
    028                if (getCurrentThreadCpuTime()==0l) {
    029                    int j=0;
    030                    for (int i=0;i<10000000;i++) j+=i;
    031                    if (getCurrentThreadCpuTime()==0l) {
    032                        sPrecise = false;
    033                        org.apache.log4j.Logger.getLogger(JProf.class).warn("Unable to mesure time in precise -- using System.currentTimeMillis().");
    034                    }
    035                }
    036            } catch (Throwable e) {
    037                org.apache.log4j.Logger.getLogger(JProf.class).warn("Unable to mesure time in precise -- using System.currentTimeMillis().");
    038                sPrecise = false;
    039            }
    040        }
    041    }