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

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

Introduction

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

Prototype

@CheckReturnValue
public static Stopwatch createStarted() 

Source Link

Document

Creates (and starts) a new stopwatch using System#nanoTime as its time source.

Usage

From source file:com.example.postgres.PostgresSqlServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

    final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( visit_id SERIAL NOT NULL, "
            + "user_ip VARCHAR(46) NOT NULL, ts timestamp NOT NULL, " + "PRIMARY KEY (visit_id) );";
    final String createVisitSql = "INSERT INTO visits (user_ip, ts) VALUES (?, ?);";
    final String selectSql = "SELECT user_ip, ts FROM visits ORDER BY ts DESC " + "LIMIT 10;";

    String path = req.getRequestURI();
    if (path.startsWith("/favicon.ico")) {
        return; // ignore the request for favicon.ico
    }/*from w  w  w. j  a va 2  s  . c  o m*/

    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");

    // store only the first two octets of a users ip address
    String userIp = req.getRemoteAddr();
    InetAddress address = InetAddress.getByName(userIp);
    if (address instanceof Inet6Address) {
        // nest indexOf calls to find the second occurrence of a character in a string
        // an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
        userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
    } else if (address instanceof Inet4Address) {
        userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
    }

    Stopwatch stopwatch = Stopwatch.createStarted();
    try (PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
        conn.createStatement().executeUpdate(createTableSql);
        statementCreateVisit.setString(1, userIp);
        statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime()));
        statementCreateVisit.executeUpdate();

        try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) {
            stopwatch.stop();
            out.print("Last 10 visits:\n");
            while (rs.next()) {
                String savedIp = rs.getString("user_ip");
                String timeStamp = rs.getString("ts");
                out.println("Time: " + timeStamp + " Addr: " + savedIp);
            }
            out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
        }
    } catch (SQLException e) {
        throw new ServletException("SQL error", e);
    }
}

From source file:nl.knaw.huygens.timbuctoo.tools.conversion.RelationCollectionConverter.java

public void convert() throws StorageException, IllegalArgumentException, IllegalAccessException {
    LOG.info("Start converting for Relation");
    try {//  w  ww  .  j a  va2  s  .c o  m

        List<String> relationIds = Lists.newArrayList();

        //first create the jobs to prevent a mongo cursor timeout exception.
        for (StorageIterator<Relation> relations = mongoStorage.getDomainEntities(Relation.class); relations
                .hasNext();) {
            relationIds.add(relations.next().getId());

        }
        int number = 0;
        Stopwatch stopwatch = Stopwatch.createStarted();
        for (String id : relationIds) {
            versionConverter.convert(id);
            if (number % 1000 == 0) {
                commit();
                LOG.info("Time per conversion: {} ms, number of conversions {}",
                        (double) stopwatch.elapsed(TimeUnit.MILLISECONDS) / number, number);
            }
            number++;

        }
    } finally {
        commit();
        LOG.info("End converting for Relation");
    }

}

From source file:org.agatom.springatom.data.oid.creators.DefaultSOidCreator.java

@Override
public SOid fromString(final String from) throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("fromString(from=%s)", from));
    }/*from  w w w.jav  a  2 s .  co m*/
    final SOid oid;
    final Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        final String split[] = from.split(":");
        Assert.isTrue(split.length == 3,
                String.format("OID[%s] is invalid, it should be in format A:B:C", from));

        final String oidPrefix = split[TYPE_PREFIX_INDEX];
        final Class<?> oidClass = Class.forName(split[CLASS_NAME_INDEX]);
        final String oidId = split[ID_INDEX];

        oid = this.getOidObject(oidPrefix, oidClass, oidId);
    } catch (Exception exp) {
        LOGGER.error(String.format("fromString(from=%s) failed...", from), Throwables.getRootCause(exp));
        throw exp;
    }

    stopwatch.stop();

    if (LOGGER.isTraceEnabled()) {
        final long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        LOGGER.trace(String.format("fromString(from=%s) to SOid(oid=%s) took %d ms", from, oid, elapsed));
    }

    return oid;
}

From source file:org.opendaylight.controller.cluster.datastore.utils.MessageTracker.java

public void begin() {
    if (enabled) {
        return;
    }
    enabled = true;
    expectedMessageWatch = Stopwatch.createStarted();
}

From source file:com.example.app.url.shortener.service.URLShortenerService.java

String tryURLShortenOperation(Function<Urlshortener, String> operation, double rate) throws IOException {
    final Stopwatch stopwatch = Stopwatch.createStarted();
    final Urlshortener shortener = createURLShortener();
    final RateLimiter rateLimiter = RateLimiter.create(rate);
    IOException lastException = null;
    int retries = 0;
    while (retries++ < 5) {
        try {//from  www.  j  av a2  s  .  c o  m
            return operation.apply(shortener);
        } catch (RuntimeException e) {
            if (e.getCause() instanceof IOException)
                lastException = (IOException) e.getCause();
            if (e.getCause() instanceof InterruptedIOException) {
                if (_logger.isDebugEnabled()) {
                    _logger.debug("Could not shorten URL due to connection error. Retry#" + retries
                            + ". Time spent: " + stopwatch, e);
                }
                rateLimiter.acquire();
            } else
                throw e;
        }
    }
    if (lastException != null)
        throw lastException;
    else
        throw new IOException("Unable to shorten URL. Retried " + retries + " times for " + stopwatch);
}

From source file:benchmarkio.consumer.activemq.ActiveMQMessageConsumer.java

@Override
public Histogram call() throws Exception {

    int messageCount = 0;

    try {//www  .ja v a2 s  .com
        // Note that this is a polling consumer and will be terminated
        // whenever the Consts.POLLING_CONSUMER_MAX_IDLE_TIME_MS passes and no new messages have arrived.
        while (true) {
            // Start
            final Stopwatch stopwatch = Stopwatch.createStarted();

            // Wait for a message
            // This is hilarious, according to the implementation javadoc comment:
            // Will return the next message produced for this message consumer, or null if
            // the timeout expires or this message consumer is concurrently closed
            final Message message = consumer.receive(Consts.POLLING_CONSUMER_MAX_IDLE_TIME_MS);

            if (message == null) {
                break;
            }

            messageCount++;

            //                if (message instanceof TextMessage) {
            //                    final TextMessage textMessage = (TextMessage) message;
            //                    final String text = textMessage.getText();
            //                    System.out.println("Received: " + text);
            //                } else {
            //                    System.out.println("Received: " + message);
            //                }

            // End
            stopwatch.stop();
            histogram.recordValue(stopwatch.elapsed(Consts.TIME_UNIT_FOR_REPORTING));
        }
    } catch (final Exception e) {
        // This is by purpose, hence no error logging.
        logger.info("Consumer was terminated through timeout");
    }

    logger.info("In total consumed {} messages", messageCount);

    return histogram;
}

From source file:es.usc.citius.composit.core.composition.search.ForwardServiceDiscoverer.java

public ServiceMatchNetwork<E, T> search(Signature<E> signature) {
    Set<E> availableInputs = new HashSet<E>(signature.getInputs());
    Set<E> newOutputs = new HashSet<E>(signature.getInputs());
    Set<E> unmatchedOutputs = new HashSet<E>(signature.getOutputs());
    Set<Operation<E>> usedServices = new HashSet<Operation<E>>();
    Map<Operation<E>, Set<E>> unmatchedInputMap = new HashMap<Operation<E>, Set<E>>();
    List<Set<Operation<E>>> leveledOps = new LinkedList<Set<Operation<E>>>();

    boolean checkExpectedOutputs = !signature.getOutputs().isEmpty();
    boolean stop;

    Stopwatch timer = Stopwatch.createStarted();
    Stopwatch levelTimer = Stopwatch.createUnstarted();
    int level = 0;
    do {//from  w  w w  .ja v a2  s  .c o m
        HashSet<Operation<E>> candidates = new HashSet<Operation<E>>();
        levelTimer.start();
        candidates.addAll(discovery.findOperationsConsumingSome(newOutputs));
        log.info("(Level {}) {} potential candidates selected in {}", level++, candidates.size(),
                levelTimer.toString());
        // Remove services that cannot be invoked with the available inputs
        for (Iterator<Operation<E>> it = candidates.iterator(); it.hasNext();) {
            Operation<E> candidate = it.next();
            // Retrieve the unmatched inputs for this operation
            Set<E> unmatchedInputs = unmatchedInputMap.get(candidate);
            if (unmatchedInputs == null) {
                unmatchedInputs = candidate.getSignature().getInputs();
            }
            // Check if the new concepts match some unmatched inputs
            Set<E> matched = matcher.partialMatch(newOutputs, unmatchedInputs).getTargetElements();

            // Don't check invokability
            if (relaxedMatchCondition) {
                // Remove only if there is no match at all
                if (matched.isEmpty()) {
                    it.remove();
                } else {
                    boolean isNew = usedServices.add(candidate);
                    if (!isNew)
                        it.remove();
                }
            } else {
                // Update the unmatchedInputs
                unmatchedInputs = Sets.newHashSet(Sets.difference(unmatchedInputs, matched));
                unmatchedInputMap.put(candidate, unmatchedInputs);
                // If there are no unmatched inputs, the service is invokable!
                if (!unmatchedInputs.isEmpty()) {
                    it.remove();
                } else {
                    // Invokable operation, check if it was used previously
                    boolean isNew = usedServices.add(candidate);
                    if (!isNew)
                        it.remove();
                }
            }
        }
        log.info("\t + [{}] operations selected for this level in {}", candidates.size(),
                levelTimer.toString());
        log.debug("\t\t Candidates: {}", candidates);

        // Collect the new outputs of the new candidates
        Set<E> nextOutputs = Operations.outputs(candidates);

        // Check unmatched outputs
        Set<E> matchedOutputs = matcher.partialMatch(Sets.union(newOutputs, nextOutputs), unmatchedOutputs)
                .getTargetElements();
        //Set<Resource> matchedOutputs = matcher.matched(newOutputs, unmatchedOutputs);
        // Update the unmatched outputs
        unmatchedOutputs = Sets.newHashSet(Sets.difference(unmatchedOutputs, matchedOutputs));

        // Update for the next iteration
        availableInputs.addAll(newOutputs);
        newOutputs = nextOutputs;

        // Add the discovered ops
        if (!candidates.isEmpty())
            leveledOps.add(candidates);

        log.debug("\t + Available inputs: {}, new outputs: {}", availableInputs.size(), newOutputs.size());
        // Stop condition. Stop if there are no more candidates and/or expected outputs are satisfied.
        stop = (checkExpectedOutputs) ? candidates.isEmpty() || unmatchedOutputs.isEmpty()
                : candidates.isEmpty();
        levelTimer.reset();
    } while (!stop);

    // Add the source and sink operations
    Source<E> sourceOp = new Source<E>(signature.getInputs());
    Sink<E> sinkOp = new Sink<E>(signature.getOutputs());
    leveledOps.add(0, Collections.<Operation<E>>singleton(sourceOp));
    leveledOps.add(leveledOps.size(), Collections.<Operation<E>>singleton(sinkOp));
    Stopwatch networkWatch = Stopwatch.createStarted();
    // Create a service match network with the discovered services
    DirectedAcyclicSMN<E, T> matchNetwork = new DirectedAcyclicSMN<E, T>(new HashLeveledServices<E>(leveledOps),
            this.matcher);
    log.info(" > Service match network computed in {}", networkWatch.stop().toString());
    log.info("Service Match Network created with {} levels (including source and sink) and {} operations.",
            leveledOps.size(), matchNetwork.listOperations().size());
    log.info("Forward Discovery done in {}", timer.toString());
    this.unmatchedInputMap = unmatchedInputMap;
    return matchNetwork;
}

From source file:com.example.cloudsql.CloudSqlServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( visit_id INT NOT NULL "
            + "AUTO_INCREMENT, user_ip VARCHAR(46) NOT NULL, timestamp DATETIME NOT NULL, "
            + "PRIMARY KEY (visit_id) )";
    final String createVisitSql = "INSERT INTO visits (user_ip, timestamp) VALUES (?, ?)";
    final String selectSql = "SELECT user_ip, timestamp FROM visits ORDER BY timestamp DESC " + "LIMIT 10";

    String path = req.getRequestURI();
    if (path.startsWith("/favicon.ico")) {
        return; // ignore the request for favicon.ico
    }/* ww w. j  a  v a 2 s  . co m*/

    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");

    // store only the first two octets of a users ip address
    String userIp = req.getRemoteAddr();
    InetAddress address = InetAddress.getByName(userIp);
    if (address instanceof Inet6Address) {
        // nest indexOf calls to find the second occurrence of a character in a string
        // an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
        userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
    } else if (address instanceof Inet4Address) {
        userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
    }

    Stopwatch stopwatch = Stopwatch.createStarted();
    try (PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
        conn.createStatement().executeUpdate(createTableSql);
        statementCreateVisit.setString(1, userIp);
        statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime()));
        statementCreateVisit.executeUpdate();

        try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) {
            stopwatch.stop();
            out.print("Last 10 visits:\n");
            while (rs.next()) {
                String savedIp = rs.getString("user_ip");
                String timeStamp = rs.getString("timestamp");
                out.print("Time: " + timeStamp + " Addr: " + savedIp + "\n");
            }
            out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
        }
    } catch (SQLException e) {
        throw new ServletException("SQL error", e);
    }
}

From source file:org.hawkular.metrics.core.jobs.DeleteExpiredMetrics.java

@Override
public Completable call(JobDetails jobDetails) {
    logger.info("Starting delete expired metrics job");
    Stopwatch stopwatch = Stopwatch.createStarted();

    String unparsedConfigExpirationTime = jobDetails.getParameters().get("expirationTimestamp");
    Long configuredExpirationTime = null;
    if (unparsedConfigExpirationTime != null && !unparsedConfigExpirationTime.isEmpty()) {
        try {/*from ww w  .j  a v  a2 s  . c om*/
            configuredExpirationTime = Long.parseLong(unparsedConfigExpirationTime);
        } catch (Exception exp) {
            //do nothing just use the default configuration
        }
    }

    long expirationTime = (configuredExpirationTime != null ? configuredExpirationTime
            : DateTimeService.now.get().getMillis()) - metricExpirationDelay;

    Observable<MetricId<?>> expirationIndexResults = session.execute(findEligibleTenants.bind())
            .flatMap(Observable::from)
            .flatMap(row -> session.execute(findEligibleMetrics.bind(row.getString(0), row.getByte(1))))
            .flatMap(Observable::from).filter(row -> row.getTimestamp(3).getTime() < expirationTime)
            .map(row -> new MetricId<>(row.getString(0), MetricType.fromCode(row.getByte(1)),
                    row.getString(2)));

    //If the compression job is disabled then check the data point table for data
    String compressJobEnabledConfig = configurationService.load(CompressData.CONFIG_ID, "enabled").toBlocking()
            .firstOrDefault(null);

    boolean compressJobEnabled = false;
    if (compressJobEnabledConfig != null && !compressJobEnabledConfig.isEmpty()) {
        try {
            compressJobEnabled = Boolean.parseBoolean(compressJobEnabledConfig);
        } catch (Exception e) {
            //do nothing, assume the compression job is disabled
        }
    }
    if (!compressJobEnabled) {
        expirationIndexResults = expirationIndexResults.flatMap(r -> session
                .execute(findUnexpiredDataPoints.bind(r.getTenantId(), r.getType().getCode(), r.getName()))
                .flatMap(Observable::from).isEmpty().filter(empty -> empty).map(empty -> r));
    }

    return expirationIndexResults.concatMap(metricId -> metricsService.deleteMetric(metricId))
            .onErrorResumeNext(e -> {
                logger.error("Failed to delete metric data", e);
                return Observable.empty();
            }).doOnError(t -> {
                stopwatch.stop();
                logger.error("The job for deleting expired metrics failed. Total run time "
                        + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms", t);
            }).doOnCompleted(() -> {
                stopwatch.stop();
                logger.info("The job for deleting expired metrics finished. Total run time "
                        + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
            }).toCompletable();
}

From source file:it.units.malelab.ege.core.evolver.StandardEvolver.java

@Override
public List<Node<T>> solve(ExecutorService executor, Random random, List<EvolverListener<G, T, F>> listeners)
        throws InterruptedException, ExecutionException {
    LoadingCache<G, Pair<Node<T>, Map<String, Object>>> mappingCache = CacheBuilder.newBuilder()
            .maximumSize(CACHE_SIZE).recordStats().build(getMappingCacheLoader());
    LoadingCache<Node<T>, F> fitnessCache = CacheBuilder.newBuilder().maximumSize(CACHE_SIZE).recordStats()
            .build(getFitnessCacheLoader());
    Stopwatch stopwatch = Stopwatch.createStarted();
    //initialize population
    int births = 0;
    List<Callable<List<Individual<G, T, F>>>> tasks = new ArrayList<>();
    for (G genotype : configuration.getPopulationInitializer().build(configuration.getPopulationSize(),
            configuration.getInitGenotypeValidator(), random)) {
        tasks.add(individualFromGenotypeCallable(genotype, 0, mappingCache, fitnessCache, listeners, null, null,
                executor));//from w  w w. j a v a 2  s. c o m
        births = births + 1;
    }
    List<Individual<G, T, F>> population = new ArrayList<>(Utils.getAll(executor.invokeAll(tasks)));
    int lastBroadcastGeneration = (int) Math
            .floor(actualBirths(births, fitnessCache) / configuration.getPopulationSize());
    Utils.broadcast(new EvolutionStartEvent<>(this, cacheStats(mappingCache, fitnessCache)), listeners,
            executor);
    Utils.broadcast(new GenerationEvent<>(configuration.getRanker().rank(population, random),
            lastBroadcastGeneration, this, cacheStats(mappingCache, fitnessCache)), listeners, executor);
    //iterate
    while (Math.round(actualBirths(births, fitnessCache) / configuration.getPopulationSize()) < configuration
            .getNumberOfGenerations()) {
        int currentGeneration = (int) Math.floor(births / configuration.getPopulationSize());
        tasks.clear();
        //re-rank
        List<List<Individual<G, T, F>>> rankedPopulation = configuration.getRanker().rank(population, random);
        //produce offsprings
        int i = 0;
        while (i < configuration.getOffspringSize()) {
            GeneticOperator<G> operator = Utils.selectRandom(configuration.getOperators(), random);
            List<Individual<G, T, F>> parents = new ArrayList<>(operator.getParentsArity());
            for (int j = 0; j < operator.getParentsArity(); j++) {
                parents.add(configuration.getParentSelector().select(rankedPopulation, random));
            }
            tasks.add(operatorApplicationCallable(operator, parents, random, currentGeneration, mappingCache,
                    fitnessCache, listeners, executor));
            i = i + operator.getChildrenArity();
        }
        List<Individual<G, T, F>> newPopulation = new ArrayList<>(Utils.getAll(executor.invokeAll(tasks)));
        births = births + newPopulation.size();
        //build new population
        if (configuration.isOverlapping()) {
            population.addAll(newPopulation);
        } else {
            if (newPopulation.size() >= configuration.getPopulationSize()) {
                population = newPopulation;
            } else {
                //keep missing individuals from old population
                int targetSize = population.size() - newPopulation.size();
                while (population.size() > targetSize) {
                    Individual<G, T, F> individual = configuration.getUnsurvivalSelector()
                            .select(rankedPopulation, random);
                    population.remove(individual);
                }
                population.addAll(newPopulation);
            }
        }
        //select survivals
        while (population.size() > configuration.getPopulationSize()) {
            //re-rank
            rankedPopulation = configuration.getRanker().rank(population, random);
            Individual<G, T, F> individual = configuration.getUnsurvivalSelector().select(rankedPopulation,
                    random);
            population.remove(individual);
        }
        if ((int) Math.floor(actualBirths(births, fitnessCache)
                / configuration.getPopulationSize()) > lastBroadcastGeneration) {
            lastBroadcastGeneration = (int) Math
                    .floor(actualBirths(births, fitnessCache) / configuration.getPopulationSize());
            Utils.broadcast(new GenerationEvent<>((List) rankedPopulation, lastBroadcastGeneration, this,
                    cacheStats(mappingCache, fitnessCache)), listeners, executor);
        }
        if (configuration.getMaxRelativeElapsed() > 0) {
            //check if relative elapsed time exceeded
            double avgFitnessComputationNanos = fitnessCache.stats().averageLoadPenalty();
            double elapsedNanos = stopwatch.elapsed(TimeUnit.NANOSECONDS);
            if (elapsedNanos / avgFitnessComputationNanos > configuration.getMaxRelativeElapsed()) {
                break;
            }
        }
        if (configuration.getMaxElapsed() > 0) {
            //check if elapsed time exceeded
            if (stopwatch.elapsed(TimeUnit.SECONDS) > configuration.getMaxElapsed()) {
                break;
            }
        }
        if (configuration.getProblem().getLearningFitnessComputer().bestValue() != null) {
            //check if optimal solution found
            if (rankedPopulation.get(0).get(0).getFitness()
                    .equals(configuration.getProblem().getLearningFitnessComputer().bestValue())) {
                break;
            }
        }
    }
    //end
    List<Node<T>> bestPhenotypes = new ArrayList<>();
    List<List<Individual<G, T, F>>> rankedPopulation = configuration.getRanker().rank(population, random);
    Utils.broadcast(new EvolutionEndEvent<>((List) rankedPopulation,
            (int) Math.floor(actualBirths(births, fitnessCache) / configuration.getPopulationSize()), this,
            cacheStats(mappingCache, fitnessCache)), listeners, executor);
    for (Individual<G, T, F> individual : rankedPopulation.get(0)) {
        bestPhenotypes.add(individual.getPhenotype());
    }
    return bestPhenotypes;
}