Example usage for org.springframework.util StopWatch getTotalTimeMillis

List of usage examples for org.springframework.util StopWatch getTotalTimeMillis

Introduction

In this page you can find the example usage for org.springframework.util StopWatch getTotalTimeMillis.

Prototype

public long getTotalTimeMillis() 

Source Link

Document

Get the total time in milliseconds for all tasks.

Usage

From source file:org.eurekastreams.server.aop.PerformanceTimer.java

/**
 * Method for logging timing data./*from   w  w  w  .  jav a2  s.  co m*/
 * 
 * @param call
 *            {@link ProceedingJoinPoint}
 * @return result of wrapped method.
 * @throws Throwable
 *             on error.
 */
public Object profile(final ProceedingJoinPoint call) throws Throwable {
    StopWatch clock = null;

    // get the perf log for target object.
    Log log = LogFactory.getLog("perf.timer." + call.getTarget().getClass().getCanonicalName());
    try {
        if (log.isInfoEnabled()) {
            clock = new StopWatch();
            clock.start(call.toShortString());
        }
        return call.proceed();
    } finally {
        if (log.isInfoEnabled() && clock != null) {
            clock.stop();

            Object[] args = call.getArgs();
            StringBuffer params = new StringBuffer();
            for (Object obj : args) {
                params.append("Param: " + ((obj == null) ? "null" : obj.toString()) + "\n\t");
            }

            log.info(clock.getTotalTimeMillis() + " (ms) - " + call.getTarget().getClass().getSimpleName() + "."
                    + call.getSignature().toShortString() + "\n\t" + params.toString());
        }

    }
}

From source file:org.hyperic.hq.monitor.aop.aspects.PerformanceMonitor.java

/**
 * We could bind the @Transactional annotation to the context but there's no
 * way to know if the method or the type is annotated, causing a false
 * negative.//  ww  w. ja  v a 2s  .  c  o m
 * @see org.hyperic.hq.monitor.aop.MonitorArchitecture
 * @param pjp
 */
@Around("org.hyperic.hq.monitor.aop.MonitorArchitecture.serviceLayerOperationDuration()")
public Object monitorServiceMethod(ProceedingJoinPoint pjp) throws Throwable {

    Object invocation = null;

    final StopWatch timer = new StopWatch(pjp.getSignature() + Thread.currentThread().getName());

    try {
        timer.start();
        invocation = pjp.proceed();
    } finally {
        timer.stop();
    }

    long duration = timer.getTotalTimeMillis();

    if (duration > maximumDuration) {
        logger.warn(new StringBuilder(warningMessage).append(pjp.getSignature()).append(" executed in ")
                .append(timer.getTotalTimeMillis()).append(":ms").toString());
    }

    return invocation;
}

From source file:org.jahia.bin.ErrorFileDumperTest.java

@Test
public void testHighLoadDeactivation() throws InterruptedException {

    logger.info("Starting testHighLoadDeactivation test...");

    RequestLoadAverage.RequestCountProvider requestCountProvider = new RequestLoadAverage.RequestCountProvider() {
        public long getRequestCount() {
            return 100;
        }//from  w ww.j  a v a2  s.c  o m
    };

    RequestLoadAverage requestLoadAverage = new RequestLoadAverage("requestLoadAverage", requestCountProvider);
    requestLoadAverage.start();
    logger.info("Waiting for load average to reach 10...");
    while (requestLoadAverage.getOneMinuteLoad() < 10.0) {
        Thread.sleep(500);
    }

    StopWatch stopWatch = new StopWatch("testHighLoadDeactivation");
    stopWatch.start(Thread.currentThread().getName() + " generating error dumps");

    int fileCountBeforeTest = 0;
    if (todaysDirectory.exists()) {
        File[] files = todaysDirectory.listFiles();
        fileCountBeforeTest = (files == null ? 0 : files.length);
    }

    ErrorFileDumper.setHighLoadBoundary(10.0);
    ErrorFileDumper.start();

    generateExceptions();

    stopWatch.stop();
    long totalTime = stopWatch.getTotalTimeMillis();
    double averageTime = ((double) totalTime) / ((double) LOOP_COUNT);
    logger.info("Milliseconds per exception = " + averageTime);
    logger.info(stopWatch.prettyPrint());

    ErrorFileDumper.shutdown(10000L);

    RequestLoadAverage.getInstance().stop();

    int fileCountAfterTest = 0;
    if (todaysDirectory.exists()) {
        File[] files = todaysDirectory.listFiles();
        fileCountAfterTest = (files == null ? 0 : files.length);
    }

    Assert.assertEquals("File count should stay the same because high load deactivates file dumping !",
            fileCountBeforeTest, fileCountAfterTest);

    requestLoadAverage = new RequestLoadAverage("requestLoadAverage");
}

From source file:org.jahia.bin.ErrorFileDumperTest.java

@Test
public void testDumperInSequence() throws InterruptedException {

    logger.info("Starting testDumperInSequence test...");

    StopWatch stopWatch = new StopWatch("testDumperInSequence");
    stopWatch.start(Thread.currentThread().getName() + " generating error dumps");

    ErrorFileDumper.start();// w  w w .jav a 2  s. c  o  m

    generateExceptions();

    stopWatch.stop();
    long totalTime = stopWatch.getTotalTimeMillis();
    double averageTime = ((double) totalTime) / ((double) LOOP_COUNT);
    logger.info("Milliseconds per exception = " + averageTime);
    logger.info(stopWatch.prettyPrint());

    ErrorFileDumper.shutdown(10000L);

    Assert.assertTrue("Error dump directory does not exist !", todaysDirectory.exists());
    Assert.assertTrue("Error dump directory should have error files in it !",
            todaysDirectory.listFiles().length > 0);
}

From source file:org.jahia.bin.ErrorFileDumperTest.java

@Test
public void testDumpErrorsToFilesSetting() throws InterruptedException {
    logger.info("Starting testDumpErrorsToFilesSetting test...");

    StopWatch stopWatch = new StopWatch("testDumpErrorsToFilesSetting");
    stopWatch.start(Thread.currentThread().getName() + " generating error dumps");

    ErrorFileDumper.start();//  w  w w  .j  a  v  a  2s  . c om
    ErrorFileDumper.setFileDumpActivated(false);

    generateExceptions();

    stopWatch.stop();
    long totalTime = stopWatch.getTotalTimeMillis();
    double averageTime = ((double) totalTime) / ((double) LOOP_COUNT);
    logger.info("Milliseconds per exception = " + averageTime);
    logger.info(stopWatch.prettyPrint());

    ErrorFileDumper.shutdown(10000L);

    SettingsBean.getInstance().setDumpErrorsToFiles(true);
    Assert.assertFalse("Error dump directory should not exist !", todaysDirectory.exists());
}

From source file:org.jahia.bin.ErrorFileDumperTest.java

@Test
public void testDumperInParallel() throws IOException, InterruptedException {

    logger.info("Starting testDumperInParallel test...");

    StopWatch stopWatch = new StopWatch("testDumperInParallel");
    stopWatch.start(Thread.currentThread().getName() + " generating error dumps");

    ErrorFileDumper.start();//w w w . j ava2  s  . co  m

    threadSet.clear();

    for (int i = 0; i < THREAD_COUNT; i++) {
        Thread newThread = new Thread(new Runnable() {

            public void run() {
                generateExceptions();
            }
        }, "ErrorFileDumperTestThread" + i);
        threadSet.add(newThread);
        newThread.start();
    }

    logger.info("Waiting for dumps to be processed...");

    for (Thread curThread : threadSet) {
        curThread.join();
    }

    ErrorFileDumper.shutdown(10000L);

    stopWatch.stop();
    long totalTime = stopWatch.getTotalTimeMillis();
    double averageTime = ((double) totalTime) / ((double) LOOP_COUNT);
    logger.info("Milliseconds per exception = " + averageTime);
    logger.info(stopWatch.prettyPrint());

    Assert.assertTrue("Error dump directory does not exist !", todaysDirectory.exists());
    Assert.assertTrue("Error dump directory should have error files in it !",
            todaysDirectory.listFiles().length > 0);
}

From source file:org.jahia.bin.ErrorFileDumperTest.java

@Test
public void testOutputSystemInfoAllInParallel() throws InterruptedException {

    logger.info("Starting testOutputSystemInfoAllInParallel test...");

    StopWatch stopWatch = new StopWatch("testDumperInParallel");
    stopWatch.start(Thread.currentThread().getName() + " generating error dumps");

    ErrorFileDumper.start();/*from w  w w . jav a 2s.c  o m*/

    threadSet.clear();
    final int[] dumpLengths = new int[(int) THREAD_COUNT];

    for (int i = 0; i < THREAD_COUNT; i++) {
        final int threadCounter = i;
        Thread newThread = new Thread(new Runnable() {

            public void run() {
                // this is the call made in errors.jsp file.
                StringWriter stringWriter = new StringWriter();
                ErrorFileDumper.outputSystemInfo(new PrintWriter(stringWriter));
                dumpLengths[threadCounter] = stringWriter.toString().length();
                stringWriter = null;
            }
        }, "ErrorFileDumperTestThread" + i);
        threadSet.add(newThread);
        newThread.start();
    }

    logger.info("Waiting for dumps to be processed...");

    for (Thread curThread : threadSet) {
        curThread.join();
    }

    ErrorFileDumper.shutdown(10000L);

    stopWatch.stop();
    long totalTime = stopWatch.getTotalTimeMillis();
    double averageTime = ((double) totalTime) / ((double) LOOP_COUNT);
    logger.info("Milliseconds per exception = " + averageTime);
    logger.info(stopWatch.prettyPrint());
    for (int dumpLength : dumpLengths) {
        Assert.assertTrue("System info dump is empty", dumpLength > 0);
    }
}

From source file:org.ownchan.server.joint.scheduler.service.SchedulerService.java

public <T> void waitForCronjobFutures(List<Future<T>> futures, String jobName, Logger jobLogger) {
    jobLogger.debug(jobName + " started...");
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();//  w  w  w . j ava  2s .  c o  m

    long countProcessed = 0;
    long countFailed = 0;
    for (Future<T> future : futures) {
        try {
            // result might be of type Void, so in fact we might not get a result at all ...
            T result = future.get();
            if (result instanceof Boolean && !(Boolean) result) {
                ++countFailed;
            }
        } catch (Exception e) {
            Throwable t = unwrapExecutionExceptionIfPossible(e);
            jobLogger.error(t.getMessage(), t);
            ++countFailed;
        }

        ++countProcessed;
    }

    stopWatch.stop();

    jobLogger.info(MESSAGE_TEMPLATE_PROCESSED, jobName, countProcessed, countFailed,
            DurationFormatUtils.formatDurationHMS(stopWatch.getTotalTimeMillis()));
}

From source file:org.patientview.monitoring.ImportMonitor.java

public static void main(String[] args) {

    int importFileCheckCount = 0;

    while (true) {
        LOGGER.info("******** Import Logger & Monitor wakes up ********");

        int monitoringFrequencyInMinutes = Integer.parseInt(getProperty("importerMonitor.frequency.minutes"));
        numberOfLinesToRead = monitoringFrequencyInMinutes / FREQUENCY_OF_LOGGING_IMPORT_FILE_COUNTS_IN_MINUTES;

        LOGGER.info("Import file counts will be logged every {} minutes, whereas a "
                + "health check will be done every {} minutes. Each monitoring will check the last {} lines "
                + "of the log",
                new Object[] { FREQUENCY_OF_LOGGING_IMPORT_FILE_COUNTS_IN_MINUTES, monitoringFrequencyInMinutes,
                        numberOfLinesToRead });

        StopWatch sw = new StopWatch();
        sw.start();/*from   www .  j a  va 2s  .  c  o m*/

        importFileCheckCount = importFileCheckCount + FREQUENCY_OF_LOGGING_IMPORT_FILE_COUNTS_IN_MINUTES;

        /**
         * Get the folders that will be monitored
         */
        List<FolderToMonitor> foldersToMonitor = getFoldersToMonitor();

        /**
         * Count the number of files in these folders
         */
        setTheNumberOfCurrentFilesToFolderObjects(foldersToMonitor);

        /**
         * Log counts to a file
         */
        logNumberOfFiles(foldersToMonitor);

        /**
         * If it is time, check the overall monitor stability as well
         */
        if (importFileCheckCount == numberOfLinesToRead) {
            monitorImportProcess(foldersToMonitor);

            importFileCheckCount = 0;
        } else {
            LOGGER.info("Next monitoring will happen in {} minutes",
                    numberOfLinesToRead - importFileCheckCount);
        }

        sw.stop();
        LOGGER.info("ImportMonitor ends, it took {} (mm:ss)",
                new SimpleDateFormat("mm:ss").format(sw.getTotalTimeMillis()));

        /**
         * Sleep for (frequency - execution time) seconds
         */
        long maxTimeToSleep = FREQUENCY_OF_LOGGING_IMPORT_FILE_COUNTS_IN_MINUTES * SECONDS_IN_MINUTE
                * MILLISECONDS;
        long executionTime = sw.getTotalTimeMillis();
        long timeToSleep = maxTimeToSleep - executionTime;

        // if execution time is more than max time to sleep, then sleep for the max time
        if (timeToSleep < 0) {
            timeToSleep = maxTimeToSleep;
        }

        LOGGER.info("ImportMonitor will now sleep for {} (mm:ss)",
                new SimpleDateFormat("mm:ss").format(timeToSleep));

        try {
            Thread.sleep(timeToSleep);
        } catch (InterruptedException e) {
            LOGGER.error("Import Monitor could not sleep: ", e); // possible insomnia
            System.exit(0);
        }
    }
}

From source file:org.springframework.aop.aspectj.autoproxy.AspectJAutoProxyCreatorTests.java

private static void assertStopWatchTimeLimit(final StopWatch sw, final long maxTimeMillis) {
    final long totalTimeMillis = sw.getTotalTimeMillis();
    assertTrue("'" + sw.getLastTaskName() + "' took too long: expected less than<" + maxTimeMillis
            + "> ms, actual<" + totalTimeMillis + "> ms.", totalTimeMillis < maxTimeMillis);
}