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

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

Introduction

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

Prototype

public Stopwatch reset() 

Source Link

Document

Sets the elapsed time for this stopwatch to zero, and places it in a stopped state.

Usage

From source file:com.b2international.snowowl.snomed.datastore.request.rf2.SnomedRf2ImportRequest.java

private void read(File rf2Archive, Rf2EffectiveTimeSlices slices, Map<String, Long> storageKeysByComponent,
        Map<String, Long> storageKeysByRefSet) {
    final CsvMapper csvMapper = new CsvMapper();
    csvMapper.enable(CsvParser.Feature.WRAP_AS_ARRAY);
    final CsvSchema schema = CsvSchema.emptySchema().withoutQuoteChar().withColumnSeparator('\t')
            .withLineSeparator("\r\n");
    final ObjectReader oReader = csvMapper.readerFor(String[].class).with(schema);

    final Stopwatch w = Stopwatch.createStarted();
    try (final ZipFile zip = new ZipFile(rf2Archive)) {
        for (ZipEntry entry : Collections.list(zip.entries())) {
            final String fileName = Paths.get(entry.getName()).getFileName().toString().toLowerCase();
            if (fileName.contains(type.toString().toLowerCase()) && fileName.endsWith(TXT_EXT)) {
                w.reset().start();
                try (final InputStream in = zip.getInputStream(entry)) {
                    readFile(entry, in, oReader, slices, storageKeysByComponent, storageKeysByRefSet);
                }/*from www  .j a va2  s . co  m*/
                System.err.println(entry.getName() + " - " + w);
            }
        }
    } catch (IOException e) {
        throw new SnowowlRuntimeException(e);
    }

    slices.flushAll();
}

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

public void run() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    try {// ww  w .j av a2 s . co  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:org.locationtech.geogig.remote.BinaryPackedObjects.java

/**
 * @return the number of objects written
 *//*from www  .jav  a 2s. c o  m*/
public long write(ObjectFunnel funnel, List<ObjectId> want, List<ObjectId> have, Set<ObjectId> sent,
        Callback callback, boolean traverseCommits, Deduplicator deduplicator) throws IOException {

    for (ObjectId i : want) {
        if (!database.exists(i)) {
            throw new NoSuchElementException(format("Wanted commit: '%s' is not known", i));
        }
    }

    LOGGER.info("scanning for previsit list...");
    Stopwatch sw = Stopwatch.createStarted();
    ImmutableList<ObjectId> needsPrevisit = traverseCommits ? scanForPrevisitList(want, have, deduplicator)
            : ImmutableList.copyOf(have);
    LOGGER.info(String.format("Previsit list built in %s for %,d ids: %s. Calculating reachable content ids...",
            sw.stop(), needsPrevisit.size(), needsPrevisit));

    deduplicator.reset();

    sw.reset().start();
    ImmutableList<ObjectId> previsitResults = reachableContentIds(needsPrevisit, deduplicator);
    LOGGER.info(String.format("reachableContentIds took %s for %,d ids", sw.stop(), previsitResults.size()));

    deduplicator.reset();

    LOGGER.info("obtaining post order iterator on range...");
    sw.reset().start();

    Iterator<RevObject> objects = PostOrderIterator.range(want, new ArrayList<ObjectId>(previsitResults),
            database, traverseCommits, deduplicator);
    long objectCount = 0;
    LOGGER.info("PostOrderIterator.range took {}", sw.stop());

    try {
        LOGGER.info("writing objects to remote...");
        while (objects.hasNext()) {
            RevObject object = objects.next();
            funnel.funnel(object);
            objectCount++;
            callback.callback(Suppliers.ofInstance(object));
        }
    } catch (IOException e) {
        String causeMessage = Throwables.getRootCause(e).getMessage();
        LOGGER.info(String.format("writing of objects failed after %,d objects. Cause: '%s'", objectCount,
                causeMessage));
        throw e;
    }
    return objectCount;
}

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

protected Callable<List<Individual<G, T, F>>> individualFromGenotypeCallable(final G genotype,
        final int generation, final LoadingCache<G, Pair<Node<T>, Map<String, Object>>> mappingCache,
        final LoadingCache<Node<T>, F> fitnessCache, final List<EvolverListener<G, T, F>> listeners,
        final GeneticOperator<G> operator, final List<Individual<G, T, F>> parents,
        final ExecutorService executor) {
    final Evolver<G, T, F> evolver = this;
    return new Callable<List<Individual<G, T, F>>>() {
        @Override//w ww.java  2  s  .c o m
        public List<Individual<G, T, F>> call() throws Exception {
            Stopwatch stopwatch = Stopwatch.createStarted();
            Pair<Node<T>, Map<String, Object>> mappingOutcome = mappingCache.getUnchecked(genotype);
            Node<T> phenotype = mappingOutcome.getFirst();
            long elapsed = stopwatch.stop().elapsed(TimeUnit.NANOSECONDS);
            Utils.broadcast(new MappingEvent<>(genotype, phenotype, elapsed, generation, evolver, null),
                    listeners, executor);
            stopwatch.reset().start();
            F fitness = fitnessCache.getUnchecked(phenotype);
            elapsed = stopwatch.stop().elapsed(TimeUnit.NANOSECONDS);
            Individual<G, T, F> individual = new Individual<>(genotype, phenotype, fitness, generation,
                    saveAncestry ? (List) parents : null, mappingOutcome.getSecond());
            Utils.broadcast(new BirthEvent<>(individual, elapsed, generation, evolver, null), listeners,
                    executor);
            return Collections.singletonList(individual);
        }
    };
}

From source file:org.geogig.osm.cli.commands.OSMHistoryImport.java

private void importOsmHistory(GeogigCLI cli, Console console, HistoryDownloader downloader,
        @Nullable Envelope featureFilter) throws IOException {

    ensureTypesExist(cli);//from w  ww .  j a v a  2 s  .c o  m

    Iterator<Changeset> changesets = downloader.fetchChangesets();

    GeoGIG geogig = cli.getGeogig();

    boolean initialized = false;
    Stopwatch sw = Stopwatch.createUnstarted();

    while (changesets.hasNext() && !silentListener.isCanceled()) {
        sw.reset().start();
        Changeset changeset = changesets.next();
        if (changeset.isOpen()) {
            throw new CommandFailedException(
                    "Can't import past changeset " + changeset.getId() + " as it is still open.");
        }
        String desc = String.format("obtaining osm changeset %,d...", changeset.getId());
        console.print(desc);
        console.flush();

        Optional<Iterator<Change>> opchanges = changeset.getChanges().get();
        if (!opchanges.isPresent()) {
            updateBranchChangeset(geogig, changeset.getId());
            console.println(" does not apply.");
            console.flush();
            sw.stop();
            continue;
        }
        Iterator<Change> changes = opchanges.get();
        console.print(" inserting...");
        console.flush();

        long changeCount = insertChanges(cli, changes, featureFilter);
        if (!silentListener.isCanceled()) {
            console.print(String.format(" Applied %,d changes, staging...", changeCount));
            console.flush();
            geogig.command(AddOp.class).setProgressListener(silentListener).call();
            commit(cli, changeset);

            if (args.autoIndex && !initialized) {
                initializeIndex(cli);
                initialized = true;
            }
        }
        console.println(String.format(" (%s)", sw.stop()));
        console.flush();
    }
}

From source file:ch.ge.ve.protopoc.service.protocol.DefaultVotingClient.java

@Override
public String confirmVote(String confirmationCredentials) throws VoteConfirmationException {
    Preconditions.checkState(publicParameters != null,
            "The public parameters need to have been retrieved first");
    Preconditions.checkState(electionSet != null, "The electionSet needs to have been retrieved first");
    Preconditions.checkState(pointMatrix != null, "The point matrix needs to have been computed first");

    Stopwatch stopwatch = Stopwatch.createStarted();
    Confirmation confirmation = voteConfirmationClientAlgorithms.genConfirmation(confirmationCredentials,
            pointMatrix, voterSelectionCounts);
    stopwatch.stop();//  ww w . jav a2s .co m
    stats.confirmationEncodingTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    List<FinalizationCodePart> finalizationCodeParts;
    try {
        finalizationCodeParts = bulletinBoardService.publishConfirmation(voterIndex, confirmation);
    } catch (IncorrectConfirmationRuntimeException e) {
        throw new VoteConfirmationException(e);
    }

    stopwatch.reset().start();
    String finalizationCode = voteConfirmationClientAlgorithms.getFinalizationCode(finalizationCodeParts);
    stopwatch.stop();
    stats.finalizationCodeComputationTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    return finalizationCode;
}

From source file:monasca.persister.repository.vertica.VerticaMetricRepo.java

@Override
public int flush(String id) throws RepoException {

    try {//from  w w w .  ja  v  a2 s  .  c om

        Stopwatch swOuter = Stopwatch.createStarted();

        Timer.Context context = commitTimer.time();

        executeBatches(id);

        writeRowsFromTempStagingTablesToPermTables(id);

        Stopwatch swInner = Stopwatch.createStarted();

        handle.commit();
        swInner.stop();

        logger.debug("[{}]: committing transaction took: {}", id, swInner);

        swInner.reset().start();
        handle.begin();
        swInner.stop();

        logger.debug("[{}]: beginning new transaction took: {}", id, swInner);

        context.stop();

        swOuter.stop();

        logger.debug(
                "[{}]: total time for writing measurements, definitions, and dimensions to vertica took {}", id,
                swOuter);

        updateIdCaches(id);

        int commitCnt = this.measurementCnt;

        this.measurementCnt = 0;

        return commitCnt;

    } catch (Exception e) {

        logger.error("[{}]: failed to write measurements, definitions, and dimensions to vertica", id, e);

        throw new RepoException("failed to commit batch to vertica", e);

    }
}

From source file:org.apache.drill.exec.client.QuerySubmitter.java

public int submitQuery(DrillClient client, String plan, String type, String format, int width)
        throws Exception {

    PrintingResultsListener listener;/* w ww  . j a  v a  2  s .co m*/

    String[] queries;
    QueryType queryType;
    type = type.toLowerCase();
    switch (type) {
    case "sql":
        queryType = QueryType.SQL;
        queries = plan.trim().split(";");
        break;
    case "logical":
        queryType = QueryType.LOGICAL;
        queries = new String[] { plan };
        break;
    case "physical":
        queryType = QueryType.PHYSICAL;
        queries = new String[] { plan };
        break;
    default:
        System.out.println("Invalid query type: " + type);
        return -1;
    }

    Format outputFormat;
    format = format.toLowerCase();
    switch (format) {
    case "csv":
        outputFormat = Format.CSV;
        break;
    case "tsv":
        outputFormat = Format.TSV;
        break;
    case "table":
        outputFormat = Format.TABLE;
        break;
    default:
        System.out.println("Invalid format type: " + format);
        return -1;
    }
    Stopwatch watch = new Stopwatch();
    for (String query : queries) {
        listener = new PrintingResultsListener(client.getConfig(), outputFormat, width);
        watch.start();
        client.runQuery(queryType, query, listener);
        int rows = listener.await();
        System.out.println(String.format("%d record%s selected (%f seconds)", rows, rows > 1 ? "s" : "",
                (float) watch.elapsed(TimeUnit.MILLISECONDS) / (float) 1000));
        if (query != queries[queries.length - 1]) {
            System.out.println();
        }
        watch.stop();
        watch.reset();
    }
    return 0;

}

From source file:org.locationtech.geogig.repository.RevTreeBuilder2.java

/**
 * Traverses the nodes in the {@link NodeIndex}, deletes the ones with {@link ObjectId#NULL
 * NULL} ObjectIds, and adds the ones with non "NULL" ids.
 * /*  w w w .j a v a 2  s .  c  o  m*/
 * @return the new tree, not saved to the object database. Any bucket tree though is saved when
 *         this method returns.
 */
public RevTree build() {
    if (nodeIndex == null) {
        return original.builder(db).build();
    }

    Stopwatch sw = Stopwatch.createStarted();
    RevTreeBuilder builder;
    try {
        builder = new RevTreeBuilder(db, original);
        Iterator<Node> nodes = nodeIndex.nodes();
        while (nodes.hasNext()) {
            Node node = nodes.next();
            if (node.getObjectId().isNull()) {
                builder.remove(node.getName());
            } else {
                builder.put(node);
            }
        }
    } catch (RuntimeException e) {
        e.printStackTrace();
        throw e;
    } finally {
        nodeIndex.close();
    }
    LOGGER.debug("Index traversed in {}", sw.stop());
    sw.reset().start();

    RevTree namedTree = builder.build();
    saveExtraFeatureTypes();
    LOGGER.debug("RevTreeBuilder.build() in {}", sw.stop());
    return namedTree;
}

From source file:ch.ge.ve.protopoc.service.protocol.DefaultVotingClient.java

@Override
public List<String> sumbitVote(String identificationCredentials, List<Integer> selections)
        throws VoteCastingException {
    Preconditions.checkState(publicParameters != null,
            "The public parameters need to have been retrieved first");
    Preconditions.checkState(electionSet != null, "The electionSet needs to have been retrieved first");

    Stopwatch stopwatch = Stopwatch.createStarted();
    List<EncryptionPublicKey> publicKeyParts = bulletinBoardService.getPublicKeyParts();
    EncryptionPublicKey systemPublicKey = keyEstablishmentAlgorithms.getPublicKey(publicKeyParts);

    BallotQueryAndRand ballotQueryAndRand = computeBallot(identificationCredentials, selections,
            systemPublicKey);/*from   w ww  .  j a  v a 2 s.  c o  m*/
    randomizations = ballotQueryAndRand.getBold_r();
    stopwatch.stop();
    stats.voteEncodingTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    List<ObliviousTransferResponse> obliviousTransferResponses = sentBallotAndQuery(
            ballotQueryAndRand.getAlpha());

    stopwatch.reset().start();
    pointMatrix = computePointMatrix(selections, obliviousTransferResponses);
    List<String> returnCodes = voteCastingClientAlgorithms.getReturnCodes(selections, pointMatrix);
    stopwatch.stop();
    stats.verificationCodesComputationTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    return returnCodes;
}