Example usage for org.apache.commons.lang.time StopWatch split

List of usage examples for org.apache.commons.lang.time StopWatch split

Introduction

In this page you can find the example usage for org.apache.commons.lang.time StopWatch split.

Prototype

public void split() 

Source Link

Document

Split the time.

This method sets the stop time of the watch to allow a time to be extracted.

Usage

From source file:MainClass.java

public static void main(String[] args) {
    StopWatch clock = new StopWatch();
    NumberFormat format = NumberFormat.getInstance();

    System.out.println("How long does it take to take the sin of 0.34 ten million times?");
    clock.start();/*from w  ww  . j a v a  2 s . c  om*/
    for (int i = 0; i < 100000000; i++) {
        Math.sin(0.34);
    }
    clock.stop();

    System.out.println("It takes " + clock.getTime() + " milliseconds");

    System.out.println("How long does it take to multiply 2 doubles one billion times?");
    clock.reset();
    clock.start();
    for (int i = 0; i < 1000000000; i++) {
        double result = 3423.2234 * 23e-4;
    }
    clock.stop();
    System.out.println("It takes " + clock.getTime() + " milliseconds.");

    System.out.println("How long does it take to add 2 ints one billion times?");
    clock.reset();
    clock.start();
    for (int i = 0; i < 1000000000; i++) {
        int result = 293842923 + 33382922;
    }
    clock.stop();
    System.out.println("It takes " + clock.getTime() + " milliseconds.");

    System.out.println("Testing the split() method.");
    clock.reset();
    clock.start();
    try {
        Thread.sleep(1000);
    } catch (Exception e) {
    }
    clock.split();
    System.out.println("Split Time after 1 sec: " + clock.getTime());
    try {
        Thread.sleep(1000);
    } catch (Exception e) {
    }
    System.out.println("Split Time after 2 sec: " + clock.getTime());
    clock.unsplit();
    try {
        Thread.sleep(1000);
    } catch (Exception e) {
    }
    System.out.println("Time after 3 sec: " + clock.getTime());

}

From source file:com.continuuity.weave.yarn.YarnWeaveController.java

@Override
protected void doStartUp() {
    super.doStartUp();

    // Submit and poll the status of the yarn application
    try {//  www.ja  va2  s  .c o  m
        processController = startUp.call();

        YarnApplicationReport report = processController.getReport();
        LOG.debug("Application {} submit", report.getApplicationId());

        YarnApplicationState state = report.getYarnApplicationState();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        stopWatch.split();
        long maxTime = TimeUnit.MILLISECONDS.convert(Constants.APPLICATION_MAX_START_SECONDS, TimeUnit.SECONDS);

        LOG.info("Checking yarn application status");
        while (!hasRun(state) && stopWatch.getSplitTime() < maxTime) {
            report = processController.getReport();
            state = report.getYarnApplicationState();
            LOG.debug("Yarn application status: {}", state);
            TimeUnit.SECONDS.sleep(1);
            stopWatch.split();
        }
        LOG.info("Yarn application is in state {}", state);
        if (state != YarnApplicationState.RUNNING) {
            LOG.info("Yarn application is not in running state. Shutting down controller.",
                    Constants.APPLICATION_MAX_START_SECONDS);
            forceShutDown();
        } else {
            try {
                URL resourceUrl = URI
                        .create(String.format("http://%s:%d", report.getHost(), report.getRpcPort()))
                        .resolve(TrackerService.PATH).toURL();
                resourcesClient = new ResourceReportClient(resourceUrl);
            } catch (IOException e) {
                resourcesClient = null;
            }
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.continuuity.weave.yarn.YarnWeaveController.java

@Override
protected void doShutDown() {
    if (processController == null) {
        LOG.warn("No process controller for application that is not submitted.");
        return;//w w w .  j a v  a2 s  . c  o m
    }

    // Wait for the stop message being processed
    try {
        Uninterruptibles.getUninterruptibly(getStopMessageFuture(), Constants.APPLICATION_MAX_STOP_SECONDS,
                TimeUnit.SECONDS);
    } catch (Exception e) {
        LOG.error("Failed to wait for stop message being processed.", e);
        // Kill the application through yarn
        kill();
    }

    // Poll application status from yarn
    try {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        stopWatch.split();
        long maxTime = TimeUnit.MILLISECONDS.convert(Constants.APPLICATION_MAX_STOP_SECONDS, TimeUnit.SECONDS);

        YarnApplicationReport report = processController.getReport();
        FinalApplicationStatus finalStatus = report.getFinalApplicationStatus();
        while (finalStatus == FinalApplicationStatus.UNDEFINED && stopWatch.getSplitTime() < maxTime) {
            LOG.debug("Yarn application final status for {} {}", report.getApplicationId(), finalStatus);
            TimeUnit.SECONDS.sleep(1);
            stopWatch.split();
            finalStatus = processController.getReport().getFinalApplicationStatus();
        }
        LOG.debug("Yarn application final status is {}", finalStatus);

        // Application not finished after max stop time, kill the application
        if (finalStatus == FinalApplicationStatus.UNDEFINED) {
            kill();
        }
    } catch (Exception e) {
        LOG.warn("Exception while waiting for application report: {}", e.getMessage(), e);
        kill();
    }

    super.doShutDown();
}

From source file:com.auditbucket.test.functional.TestAuditIntegration.java

private void validateLogsIndexed(ArrayList<Long> list, int auditMax, int expectedLogCount) throws Exception {
    logger.info("Validating logs are indexed");
    int fortress = 2;
    int audit = 1;
    //DecimalFormat f = new DecimalFormat("##.000");
    while (fortress <= fortressMax) {
        while (audit <= auditMax) {
            MetaHeader header = trackService.findByCallerRefFull(list.get(fortress), "CompanyNode",
                    "ABC" + audit);
            StopWatch watch = new StopWatch();
            watch.start();//from  ww  w  . j  ava2s .  c om
            Set<TrackLog> logs = trackService.getLogs(header.getId());
            watch.split();
            assertNotNull(logs);
            //logger.info("retrieved [{}] logs in [{}] millis", logs.size(), f.format(watch.getSplitTime()));
            assertEquals("Wrong number of logs returned", expectedLogCount, logs.size());
            for (TrackLog log : logs) {
                assertEquals("logId [" + log.getId() + "] changeId[" + log.getChange().getId() + "], event[ "
                        + log.getChange().getEvent() + "]", true, log.isIndexed());
            }

            audit++;
        } // Audit headers finished with
        fortress++;
    }

}

From source file:io.cloudslang.engine.queue.services.ExecutionQueueServiceImpl.java

@Override
@Transactional/*from   w  w w.j  a  va2  s  .c  o m*/
public void enqueue(List<ExecutionMessage> messages) {
    if (CollectionUtils.isEmpty(messages))
        return;

    if (logger.isDebugEnabled())
        logger.debug("Enqueue " + messages.size() + " messages");
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    // assign worker for messages with pending status
    messages = executionAssignerService.assignWorkers(messages);
    if (logger.isDebugEnabled())
        logger.debug("Messages were assigned successfully");

    final List<ExecutionMessage> stateMessages = new ArrayList<>(messages.size());

    // first fill the execution state id for new insert
    for (ExecutionMessage msg : messages) {
        if (msg.getExecStateId() == ExecutionMessage.EMPTY_EXEC_STATE_ID) {
            long execStateId = executionQueueRepository.generateExecStateId();
            msg.setExecStateId(execStateId);
            stateMessages.add(msg);
        } else if (msg.getPayload() != null && msg.getStatus() == ExecStatus.IN_PROGRESS) {
            stateMessages.add(msg);
        }
    }

    if (CollectionUtils.isNotEmpty(listeners)) {
        stopWatch.split();
        for (QueueListener listener : listeners) {
            listener.prePersist(messages);
        }
        if (logger.isDebugEnabled())
            logger.debug("Listeners done in " + (stopWatch.getSplitTime()) + " ms");
    }

    stopWatch.split();
    if (stateMessages.size() > 0)
        executionQueueRepository.insertExecutionStates(stateMessages);

    long msgVersion = versionService.getCurrentVersion(VersionService.MSG_RECOVERY_VERSION_COUNTER_NAME);
    executionQueueRepository.insertExecutionQueue(messages, msgVersion);
    if (logger.isDebugEnabled())
        logger.debug("Persistency done in " + (stopWatch.getSplitTime()) + " ms");

    if (CollectionUtils.isNotEmpty(listeners)) {
        stopWatch.split();
        List<ExecutionMessage> failedMessages = filter(messages, ExecStatus.FAILED);
        List<ExecutionMessage> terminatedMessages = filter(messages, ExecStatus.TERMINATED);
        for (QueueListener listener : listeners) {
            listener.onEnqueue(messages, messages.size());
            if (failedMessages.size() > 0)
                listener.onFailed(failedMessages);
            if (terminatedMessages.size() > 0)
                listener.onTerminated(terminatedMessages);
        }
        if (logger.isDebugEnabled())
            logger.debug("Listeners done in " + (stopWatch.getSplitTime()) + " ms");
    }
    if (logger.isDebugEnabled())
        logger.debug("Enqueue done in " + (stopWatch.getTime()) + " ms");
}

From source file:de.pro.dbw.application.testdata.service.ReflectionService.java

@Override
protected Task<Void> createTask() {
    return new Task<Void>() {
        {//  w w  w  .  j a v a  2  s. c  om
            updateProgress(0, saveMaxEntities);
        }

        @Override
        protected Void call() throws Exception {
            LoggerFacade.INSTANCE.deactivate(Boolean.TRUE);

            final StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            final ICrudService crudService = DatabaseFacade.INSTANCE.getCrudService(entityName);
            long id = -1_000_000_000L + DatabaseFacade.INSTANCE.getCrudService().count(entityName);
            for (int i = 1; i <= saveMaxEntities; i++) {
                crudService.beginTransaction();

                final ReflectionModel model = new ReflectionModel();
                model.setGenerationTime(ReflectionService.this.createGenerationTime());
                model.setId(id++);
                model.setTitle(LoremIpsum.getDefault().getTitle());
                model.setText(LoremIpsum.getDefault().getText());

                crudService.create(model, false);
                updateProgress(i - 1, saveMaxEntities);

                crudService.commitTransaction();
            }

            LoggerFacade.INSTANCE.deactivate(Boolean.FALSE);
            stopWatch.split();
            LoggerFacade.INSTANCE.debug(this.getClass(),
                    "  + " + stopWatch.toSplitString() + " for " + saveMaxEntities + " Reflections."); // NOI18N
            stopWatch.stop();

            return null;
        }
    };
}

From source file:de.pro.dbw.application.testdata.service.DreamService.java

@Override
protected Task<Void> createTask() {
    return new Task<Void>() {
        {//from  ww  w . j  a  v  a 2  s  .  c  o  m
            updateProgress(0, saveMaxEntities);
        }

        @Override
        protected Void call() throws Exception {
            LoggerFacade.INSTANCE.deactivate(Boolean.TRUE);

            final StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            final ICrudService crudService = DatabaseFacade.INSTANCE.getCrudService(entityName);
            long id = -1_000_000_000L + DatabaseFacade.INSTANCE.getCrudService().count(entityName);
            for (int i = 1; i <= saveMaxEntities; i++) {
                crudService.beginTransaction();

                final DreamModel model = new DreamModel();
                model.setGenerationTime(DreamService.this.createGenerationTime());
                model.setDescription(LoremIpsum.getDefault().getDescription());
                model.setId(id++);
                model.setTitle(LoremIpsum.getDefault().getTitle());
                model.setText(LoremIpsum.getDefault().getText());

                crudService.create(model, false);
                updateProgress(i - 1, saveMaxEntities);

                crudService.commitTransaction();
            }

            LoggerFacade.INSTANCE.deactivate(Boolean.FALSE);
            stopWatch.split();
            LoggerFacade.INSTANCE.debug(this.getClass(),
                    "  + " + stopWatch.toSplitString() + " for " + saveMaxEntities + " Dreams."); // NOI18N
            stopWatch.stop();

            return null;
        }
    };
}

From source file:com.auditbucket.test.functional.TestForceDuplicateRlx.java

@Test
public void uniqueChangeRLXUnderLoad() throws Exception {
    logger.info("uniqueChangeRLXUnderLoad started");
    SecurityContextHolder.getContext().setAuthentication(authMike);
    regService.registerSystemUser(new RegistrationBean("TestTrack", mike, "bah").setIsUnique(false));

    int auditMax = 10;
    int logMax = 10;
    int fortress = 1;
    String simpleJson = "{\"who\":";
    ArrayList<Long> list = new ArrayList<>();

    logger.info("FortressCount: " + fortressMax + " AuditCount: " + auditMax + " LogCount: " + logMax);
    logger.info(//  w w w  . j  a  va  2  s  .c  om
            "We will be expecting a total of " + (auditMax * logMax * fortressMax) + " messages to be handled");

    StopWatch watch = new StopWatch();
    watch.start();
    double splitTotals = 0;
    long totalRows = 0;
    int auditSleepCount; // Discount all the time we spent sleeping

    DecimalFormat f = new DecimalFormat("##.000");

    while (fortress <= fortressMax) {
        String fortressName = "bulkloada" + fortress;
        int audit = 1;
        long requests = 0;
        auditSleepCount = 0;

        Fortress iFortress = fortressService.registerFortress(new FortressInputBean(fortressName, true));
        requests++;
        logger.info("Starting run for " + fortressName);
        while (audit <= auditMax) {
            MetaInputBean aib = new MetaInputBean(iFortress.getName(), fortress + "olivia@sunnybell.com",
                    "CompanyNode", new DateTime(), "ABC" + audit);
            TrackResultBean arb = trackEP.trackHeader(aib, null, null).getBody();
            requests++;
            int log = 1;
            while (log <= logMax) {
                createLog(simpleJson, aib, arb, log);
                requests++;
                log++;
            } // Logs created
            audit++;
        } // Audit headers finished with
        watch.split();
        double fortressRunTime = (watch.getSplitTime() - auditSleepCount) / 1000d;
        logger.info("*** " + iFortress.getName() + " took " + fortressRunTime + "  avg processing time for ["
                + requests + "] RPS= " + f.format(fortressRunTime / requests) + ". Requests per second "
                + f.format(requests / fortressRunTime));

        splitTotals = splitTotals + fortressRunTime;
        totalRows = totalRows + requests;
        watch.reset();
        watch.start();
        list.add(iFortress.getId());
        fortress++;
    }

    logger.info("*** Created data set in " + f.format(splitTotals) + " fortress avg = "
            + f.format(splitTotals / fortressMax) + " avg processing time per request "
            + f.format(splitTotals / totalRows) + ". Requests per second " + f.format(totalRows / splitTotals));
    watch.reset();
}

From source file:de.pro.dbw.application.testdata.service.TipOfTheNightService.java

@Override
protected Task<Void> createTask() {
    return new Task<Void>() {
        {//from   ww  w .  j  ava  2 s.com
            updateProgress(0, saveMaxEntities);
        }

        @Override
        protected Void call() throws Exception {
            LoggerFacade.INSTANCE.deactivate(Boolean.TRUE);

            final StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            final ICrudService crudService = DatabaseFacade.INSTANCE.getCrudService(entityName);
            //                crudService.beginTransaction();
            long id = -1_000_000_000L + DatabaseFacade.INSTANCE.getCrudService().count(entityName);
            for (int i = 1; i <= saveMaxEntities; i++) {
                crudService.beginTransaction();

                final TipOfTheNightModel model = new TipOfTheNightModel();
                model.setGenerationTime(TipOfTheNightService.this.createGenerationTime());
                model.setId(id++);
                model.setTitle(LoremIpsum.getDefault().getTitle());
                model.setText(LoremIpsum.getDefault()
                        .getTextWithMaxEntries(LoremIpsum.MAX_ENTRIES_FOR__TIP_OF_THE_NIGHT));

                crudService.create(model, false);
                updateProgress(i - 1, saveMaxEntities);

                crudService.commitTransaction();
                //                    if (i % 250 == 0) {
                //                        crudService.commitTransaction();
                //                        crudService.beginTransaction();
                //                    }
            }

            //                crudService.commitTransaction();

            LoggerFacade.INSTANCE.deactivate(Boolean.FALSE);
            stopWatch.split();
            LoggerFacade.INSTANCE.debug(this.getClass(),
                    "  + " + stopWatch.toSplitString() + " for " + saveMaxEntities + " TipOfTheNights."); // NOI18N
            stopWatch.stop();

            return null;
        }
    };
}

From source file:com.auditbucket.test.functional.TestAuditIntegration.java

@Test
public void stressWithHighVolume() throws Exception {
    assumeTrue(!ignoreMe);//from   ww w  . j  a v a  2 s  . c o m
    logger.info("stressWithHighVolume started");
    SecurityContextHolder.getContext().setAuthentication(authA);
    //Neo4jHelper.cleanDb(graphDatabaseService, true);
    regService.registerSystemUser(new RegistrationBean("TestTrack", email, "bah"));

    int auditMax = 10;
    int logMax = 10;
    int fortress = 1;
    //fortressMax = 10;
    String simpleJson = "{\"who\":";
    ArrayList<Long> list = new ArrayList<>();

    logger.info("FortressCount: " + fortressMax + " AuditCount: " + auditMax + " LogCount: " + logMax);
    logger.info(
            "We will be expecting a total of " + (auditMax * logMax * fortressMax) + " messages to be handled");

    StopWatch watch = new StopWatch();
    watch.start();
    double splitTotals = 0;
    long totalRows = 0;
    int auditSleepCount; // Discount all the time we spent sleeping

    DecimalFormat f = new DecimalFormat("##.000");

    while (fortress <= fortressMax) {
        String fortressName = "bulkloada" + fortress;
        int audit = 1;
        long requests = 0;
        auditSleepCount = 0;

        Fortress iFortress = fortressService.registerFortress(new FortressInputBean(fortressName, false));
        requests++;
        logger.info("Starting run for " + fortressName);
        while (audit <= auditMax) {
            boolean searchChecked = false;
            MetaInputBean aib = new MetaInputBean(iFortress.getName(), fortress + "olivia@sunnybell.com",
                    "CompanyNode", new DateTime(), "ABC" + audit);
            TrackResultBean arb = mediationFacade.createHeader(aib, null);
            requests++;
            int log = 1;
            while (log <= logMax) {
                //String escJson = Helper.getBigJsonText(log);
                //trackService.createLog(new LogInputBean(arb.getMetaKey(), aib.getFortressUser(), new DateTime(), escJson ));

                createLog(simpleJson, aib, arb, log);
                //Thread.sleep(100);
                requests++;
                if (!searchChecked) {
                    searchChecked = true;
                    MetaHeader metaHeader = trackService.getHeader(arb.getMetaKey());
                    requests++;
                    int checkCount = waitForHeaderToUpdate(metaHeader);
                    auditSleepCount = auditSleepCount + (400 * checkCount);
                    requests = requests + checkCount;
                } // searchCheck done
                log++;
            } // Logs created
            audit++;
        } // Audit headers finished with
        watch.split();
        double fortressRunTime = (watch.getSplitTime() - auditSleepCount) / 1000d;
        logger.info("*** " + iFortress.getName() + " took " + fortressRunTime + "  avg processing time for ["
                + requests + "] RPS= " + f.format(fortressRunTime / requests) + ". Requests per second "
                + f.format(requests / fortressRunTime));

        splitTotals = splitTotals + fortressRunTime;
        totalRows = totalRows + requests;
        watch.reset();
        watch.start();
        list.add(iFortress.getId());
        fortress++;
    }

    logger.info("*** Created data set in " + f.format(splitTotals) + " fortress avg = "
            + f.format(splitTotals / fortressMax) + " avg processing time per request "
            + f.format(splitTotals / totalRows) + ". Requests per second " + f.format(totalRows / splitTotals));
    watch.reset();
    Thread.sleep(5000); // give things a final chance to complete

    validateLogsIndexed(list, auditMax, logMax);
    doSearchTests(auditMax, list, watch);
}