Example usage for com.google.common.base Stopwatch Stopwatch

List of usage examples for com.google.common.base Stopwatch Stopwatch

Introduction

In this page you can find the example usage for com.google.common.base Stopwatch Stopwatch.

Prototype

Stopwatch() 

Source Link

Usage

From source file:pro.foundev.examples.spark_streaming.java.interactive.smartconsumer.DeduplicatingRabbitMQConsumer.java

public void run() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    try {/*w w w  .  j  a  v  a 2 s  . c o m*/
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(EXCHANGE_NAME, true, consumer);
        Set<String> messages = new HashSet<>();
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.start();
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            messages.add(message);

            if (stopwatch.elapsed(TimeUnit.MILLISECONDS) > 1000l) {
                System.out.println("it should be safe to submit messages now");
                for (String m : messages) {
                    //notifying user interface
                    System.out.println(m);
                }
                stopwatch.stop();
                stopwatch.reset();
                messages.clear();
            }
            if (messages.size() > 100000000) {
                System.out.println("save off to file system and clear before we lose everything");
                messages.clear();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.Grande.GSM.BACCWS_WAR.WS.REST.EOS.CPEEndpoint.java

@GET
public String fetchDHCPInfoByMAC(@QueryParam("mac") final String strMac) {

    // <editor-fold defaultstate="collapsed" desc="****** Method vars ******">
    final Stopwatch timer = new Stopwatch();
    final QueryResponse qRes = new QueryResponse();
    String strResponse = null;//from  ww w .  j  a v a 2s  . c om
    List lstCPE = null;
    // start the execution timer
    timer.start();
    // </editor-fold>

    try {

        qRes.vSetNode(java.net.InetAddress.getLocalHost().getHostName());
        lstCPE = this.bacEJB.mapFetchCPEByMac(strMac);
        qRes.vSetSuccessFlag(true);
        qRes.vSquashResult(lstCPE);

    } catch (Exception e) {

        // <editor-fold defaultstate="collapsed" desc="****** Handle failures ******">
        qRes.vSetSuccessFlag(false);
        // handle NPE differently since getMessage() is null
        if (e instanceof NullPointerException) {
            qRes.vSetMessage("NPE occured when serializing result to JSON! " + "File: "
                    + e.getStackTrace()[0].getFileName() + ", " + "Method: "
                    + e.getStackTrace()[0].getMethodName() + ", " + "Line: "
                    + e.getStackTrace()[0].getLineNumber());
        } else {
            qRes.vSetMessage(e.getMessage());
        }
        SimpleLogging.vLogException(this.strThreadId, e);
        // </editor-fold>

    } finally {

        // <editor-fold defaultstate="collapsed" desc="****** Stop timer, convert response to JSON ******">
        timer.stop();
        qRes.vSetRoundTrip(String.valueOf(timer.elapsedTime(TimeUnit.SECONDS)) + "."
                + String.valueOf(timer.elapsedTime(TimeUnit.MILLISECONDS)));
        strResponse = this.trnBN.strQueryResponseToJSON(qRes);
        SimpleLogging.vLogEvent(this.strThreadId + "|" + qRes.strGetRoundTripInSeconds() + "s",
                "retrieved " + qRes.intGetDataCount() + " records");
        // </editor-fold>

    }
    return strResponse;

}

From source file:com.dvdprime.server.mobile.listener.ResourceWarmupListener.java

@Override
public void contextInitialized(ServletContextEvent event) {
    Stopwatch sw = new Stopwatch().start();
    logger.info("---------------------------------------------------------------");
    logger.info("--- START RESTful");
    logger.info("---------------------------------------------------------------");

    try {/*  www .  j a va 2 s.c  o  m*/
        logger.info("--- connect mysql  ---");
        DaoFactory.getInstance();
        logger.info("--- start notification manager ---");
        ncWorker.start();
        logger.info("------------------------------------------------------------------------");
        logger.info("SUCCESS RESTful");
    } catch (Exception e) {
        logger.error("caught a " + e.getClass() + " with message: " + e.getMessage(), e);
        logger.info("------------------------------------------------------------------------");
        logger.info("ERROR RESTful");
    } finally {
        logger.info("------------------------------------------------------------------------");
        logger.info("Total time: {}{}", sw.elapsed(TimeUnit.SECONDS), "s");
        logger.info("Finished at: {}", new Date());
        logger.info("------------------------------------------------------------------------");
    }
}

From source file:com.pedra.storefront.filters.RequestLoggerFilter.java

@Override
public void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    if (LOG.isDebugEnabled()) {
        final String requestDetails = buildRequestDetails(request);

        if (LOG.isDebugEnabled()) {
            LOG.debug(requestDetails + "Begin");
        }/*from   ww w  . ja v  a  2  s. com*/

        logCookies(request);

        final ResponseWrapper wrappedResponse = new ResponseWrapper(response);

        final Stopwatch stopwatch = new Stopwatch();
        stopwatch.start();
        try {
            filterChain.doFilter(request, wrappedResponse);
        } finally {
            stopwatch.stop();
            final int status = wrappedResponse.getStatus();

            if (status != 0) {
                LOG.debug(requestDetails + stopwatch.toString() + " (" + status + ")");
            } else {
                LOG.debug(requestDetails + stopwatch.toString());
            }
        }

        return;
    }

    filterChain.doFilter(request, response);
}

From source file:org.apache.omid.tso.MonitoringContextImpl.java

public void timerStart(String name) {
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.start();
    timers.put(name, stopwatch);
}

From source file:processing.BaselineCalculator.java

private static List<int[]> getPopularTags(BookmarkReader reader, int sampleSize, int limit) {
    timeString = "";
    List<int[]> tags = new ArrayList<int[]>();
    Stopwatch timer = new Stopwatch();
    timer.start();//from w  ww . jav  a  2s .  c o m

    int[] tagIDs = getPopularTagList(reader, limit);

    timer.stop();
    long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
    timer = new Stopwatch();
    timer.start();
    for (int j = 0; j < sampleSize; j++) {
        tags.add(tagIDs);
    }
    timer.stop();
    long testTime = timer.elapsed(TimeUnit.MILLISECONDS);
    timeString += ("Full training time: " + trainingTime + "\n");
    timeString += ("Full test time: " + testTime + "\n");
    timeString += ("Average test time: " + testTime / sampleSize) + "\n";
    timeString += ("Total time: " + (trainingTime + testTime) + "\n");
    return tags;
}

From source file:processing.MPCalculator.java

private static List<int[]> getPopularTags(BookmarkReader reader, int sampleSize, int limit) {
    List<int[]> tags = new ArrayList<int[]>();
    Stopwatch timer = new Stopwatch();
    timer.start();/*from  www.jav a 2  s  .  c o m*/

    int[] tagIDs = getPopularTagList(reader, limit);

    timer.stop();
    long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
    timer.reset();
    timer.start();
    for (int j = 0; j < sampleSize; j++) {
        tags.add(tagIDs);
    }
    timer.stop();
    long testTime = timer.elapsed(TimeUnit.MILLISECONDS);

    timeString = PerformanceMeasurement.addTimeMeasurement(timeString, true, trainingTime, testTime,
            sampleSize);
    return tags;
}

From source file:com.Grande.GSM.BACCWS_WAR.WS.REST.EOS.BACCAdminEndpoint.java

@Path("/AllowedDevices")
@GET/*w w  w.  j a  va  2 s .c om*/
public String fetchAllowedDevices() {

    // <editor-fold defaultstate="collapsed" desc="****** Method vars ******">
    final Stopwatch timer = new Stopwatch();
    final QueryResponse qRes = new QueryResponse();
    String strResponse = null;
    List lstResult = null;
    // start the execution timer
    timer.start();
    // </editor-fold>

    try {

        qRes.vSetNode(java.net.InetAddress.getLocalHost().getHostName());
        lstResult = this.bacEJB.lstFetchAllowedDeviceTypes();
        qRes.vSetSuccessFlag(true);
        qRes.vSquashResult(lstResult);

    } catch (Exception e) {

        // <editor-fold defaultstate="collapsed" desc="****** Handle failures ******">
        qRes.vSetSuccessFlag(false);
        // handle NPE differently since getMessage() is null
        if (e instanceof NullPointerException) {
            qRes.vSetMessage("NPE occured when serializing result to JSON! " + "File: "
                    + e.getStackTrace()[0].getFileName() + ", " + "Method: "
                    + e.getStackTrace()[0].getMethodName() + ", " + "Line: "
                    + e.getStackTrace()[0].getLineNumber());
        } else {
            qRes.vSetMessage(e.getMessage());
        }
        SimpleLogging.vLogException(this.strThreadId, e);
        // </editor-fold>

    } finally {

        // <editor-fold defaultstate="collapsed" desc="****** Stop timer, convert response to JSON ******">
        timer.stop();
        qRes.vSetRoundTrip(String.valueOf(timer.elapsedTime(TimeUnit.SECONDS)) + "."
                + String.valueOf(timer.elapsedTime(TimeUnit.MILLISECONDS)));
        strResponse = this.trnBN.strQueryResponseToJSON(qRes);
        SimpleLogging.vLogEvent(this.strThreadId + "|" + qRes.strGetRoundTripInSeconds() + "s",
                "retrieved " + qRes.intGetDataCount() + " records");
        // </editor-fold>

    }
    return strResponse;

}

From source file:eugene.simulation.agent.impl.StartAgentsBehaviour.java

@Override
public void action() {
    final Set<String> started = new HashSet<String>();
    final Stopwatch stopwatch = new Stopwatch().start();
    try {/* w ww  . j a  va  2s.  c  o  m*/
        int i = 0;
        for (final Agent a : agents) {
            final Simulation simulation = new SimulationImpl(myAgent.getAID(), marketAgent.getObject(), symbol);
            a.setArguments(new Simulation[] { simulation });
            final AgentContainer container = myAgent.getContainerController();
            final AgentController controller = container.acceptNewAgent(a.getClass().getSimpleName() + i++, a);
            controller.start();
            started.add(controller.getName());
        }

        LOG.info("Starting agents took {}", stopwatch.stop());
        result.success(started);
    } catch (StaleProxyException e) {
        LOG.error(ERROR_MSG, e);
        result.fail(started);
    }
}

From source file:demos.SynchronousInsert.java

public void run() {
    logger.info("Preparing to insert metric data points");

    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    Session session = cluster.connect("demo");
    PreparedStatement insert = session
            .prepare("insert into metric_data (metric_id, time, value) values (?, ?, ?)");
    Random random = new Random();
    DateTime time = DateTime.now().minusYears(1);

    Stopwatch stopwatch = new Stopwatch().start();
    for (int i = 0; i < NUM_INSERTS; ++i) {
        String metricId = "metric-" + Math.abs(random.nextInt() % NUM_METRICS);
        double value = random.nextDouble();
        session.execute(insert.bind(metricId, time.toDate(), value));
        time = time.plusSeconds(10);/*from   www  .j a  v  a  2  s . c  o m*/
    }
    stopwatch.stop();

    logger.info("Finished inserting {} data points in {} ms", NUM_INSERTS,
            stopwatch.elapsed(TimeUnit.MILLISECONDS));
}