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

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

Introduction

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

Prototype

@CheckReturnValue
public long elapsed(TimeUnit desiredUnit) 

Source Link

Document

Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, with any fraction rounded down.

Usage

From source file:org.apache.drill.exec.rpc.BasicServer.java

@Override
public void close() throws IOException {
    try {//w ww .  j  a v  a 2  s  .c  o m
        Stopwatch watch = Stopwatch.createStarted();
        // this takes 1s to complete
        // known issue: https://github.com/netty/netty/issues/2545
        eventLoopGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS).get();
        long elapsed = watch.elapsed(MILLISECONDS);
        if (elapsed > 500) {
            logger.info("closed eventLoopGroup " + eventLoopGroup + " in " + elapsed + " ms");
        }
    } catch (final InterruptedException | ExecutionException e) {
        logger.warn("Failure while shutting down {}. ", this.getClass().getName(), e);

        // Preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the
        // interruption and respond to it if it wants to.
        Thread.currentThread().interrupt();
    }
}

From source file:org.glowroot.agent.embedded.repo.RepoAdminImpl.java

@Override
public TraceCounts analyzeTraceCounts() throws Exception {
    return dataSource.suppressQueryTimeout(new Callable<TraceCounts>() {
        @Override/*from www  .java 2s  .  co  m*/
        public TraceCounts call() throws Exception {
            ImmutableTraceCounts.Builder builder = ImmutableTraceCounts.builder();
            Stopwatch stopwatch = Stopwatch.createStarted();
            builder.addAllOverallCounts(dataSource.query(new TraceOverallCountQuery()));
            // sleep a bit to allow some other threads to use the data source
            MILLISECONDS.sleep(stopwatch.elapsed(MILLISECONDS) / 10);
            builder.addAllCounts(dataSource.query(new TraceCountQuery()));
            return builder.build();
        }
    });
}

From source file:org.apache.drill.exec.store.AffinityCalculator.java

/**
 * Builds a mapping of drillbit endpoints to hostnames
 *///from w  w  w .j  av a 2  s  .  co  m
private void buildEndpointMap() {
    Stopwatch watch = new Stopwatch();
    watch.start();
    endPointMap = new HashMap<String, DrillbitEndpoint>();
    for (DrillbitEndpoint d : endpoints) {
        String hostName = d.getAddress();
        endPointMap.put(hostName, d);
    }
    watch.stop();
    logger.debug("Took {} ms to build endpoint map", watch.elapsed(TimeUnit.MILLISECONDS));
}

From source file:appeng.hooks.TickHandler.java

private void processQueue(final Queue<IWorldCallable<?>> queue, final World world) {
    if (queue == null) {
        return;// www  .  j a va2  s .c  o m
    }

    final Stopwatch sw = Stopwatch.createStarted();

    IWorldCallable<?> c = null;
    while ((c = queue.poll()) != null) {
        try {
            c.call(world);

            if (sw.elapsed(TimeUnit.MILLISECONDS) > 50) {
                break;
            }
        } catch (final Exception e) {
            AELog.debug(e);
        }
    }

    // long time = sw.elapsed( TimeUnit.MILLISECONDS );
    // if ( time > 0 )
    // AELog.info( "processQueue Time: " + time + "ms" );
}

From source file:com.isotrol.impe3.core.engine.AbstractHTMLRenderingEngine.java

final HTMLFragment timed(final Ok result, final String name, final UUID cipId, final HTMLFragment f) {
    if (f == null) {
        return null;
    }/*from w  ww . j av  a  2 s  .  c om*/
    return new HTMLFragment() {
        public void writeTo(OutputStream output, Charset charset) throws IOException {
            final Stopwatch w = Stopwatch.createStarted();
            try {
                f.writeTo(output, charset);
            } finally {
                final long t = w.elapsed(TimeUnit.MILLISECONDS);
                if (t > 150) {
                    logger.warn(String.format("CIP [%s]-[%s] took [%d] ms to render [%s]", cipId,
                            result.getCips().get(cipId).getCip().getDefinition().getType(), t, name));
                }
            }
        }
    };

}

From source file:org.apache.pulsar.functions.worker.SchedulerManager.java

private static Producer<byte[]> createProducer(PulsarClient client, WorkerConfig config) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    for (int i = 0; i < 6; i++) {
        try {/*from   www. jav  a2  s  .  co  m*/
            return client.newProducer().topic(config.getFunctionAssignmentTopic()).enableBatching(false)
                    .blockIfQueueFull(true).compressionType(CompressionType.LZ4)
                    .sendTimeout(0, TimeUnit.MILLISECONDS).createAsync().get(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("Interrupted at creating producer to topic {}", config.getFunctionAssignmentTopic(), e);
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            log.error("Encountered exceptions at creating producer for topic {}",
                    config.getFunctionAssignmentTopic(), e);
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            try {
                log.info(
                        "Can't create a producer on assignment topic {} in {} seconds, retry in 10 seconds ...",
                        stopwatch.elapsed(TimeUnit.SECONDS));
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e1) {
                log.error("Interrupted at creating producer to topic {}", config.getFunctionAssignmentTopic(),
                        e);
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            continue;
        }
    }
    throw new RuntimeException(
            "Can't create a producer on assignment topic " + config.getFunctionAssignmentTopic() + " in "
                    + stopwatch.elapsed(TimeUnit.SECONDS) + " seconds, fail fast ...");
}

From source file:eu.project.ttc.models.occstore.MongoDBOccurrenceStore.java

private void sync() {
    LOGGER.info("Synchronizing with executor and mongoDB server");
    monitor.log();//from   w  w  w  .jav  a  2s.  c om
    LOGGER.debug("Waiting for executor to finished queued tasks");
    Stopwatch sw = Stopwatch.createStarted();
    executor.sync();
    LOGGER.debug("Executor synchronized in {}ms", sw.elapsed(TimeUnit.MILLISECONDS));
    monitor.log();
    sw = Stopwatch.createStarted();
    LOGGER.debug("Synchronizing with MongoDB server");
    mongoClient.fsync(false);
    LOGGER.debug("MongoDB synchronized in {}ms", sw.elapsed(TimeUnit.MILLISECONDS));
}

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

protected Callable<List<Individual<G, T, F>>> operatorApplicationCallable(final GeneticOperator<G> operator,
        final List<Individual<G, T, F>> parents, final Random random, 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 ExecutorService executor) {
    final Evolver<G, T, F> evolver = this;
    return new Callable<List<Individual<G, T, F>>>() {
        @Override//from   w  w  w  .j  av a  2  s . co  m
        public List<Individual<G, T, F>> call() throws Exception {
            List<Individual<G, T, F>> children = new ArrayList<>(operator.getChildrenArity());
            List<G> parentGenotypes = new ArrayList<>(operator.getParentsArity());
            for (Individual<G, T, F> parent : parents) {
                parentGenotypes.add(parent.getGenotype());
            }
            Stopwatch stopwatch = Stopwatch.createStarted();
            List<G> childGenotypes = operator.apply(parentGenotypes, random).subList(0,
                    operator.getChildrenArity());
            long elapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);
            if (childGenotypes != null) {
                for (G childGenotype : childGenotypes) {
                    children.addAll(individualFromGenotypeCallable(childGenotype, generation, mappingCache,
                            fitnessCache, listeners, operator, parents, executor).call());
                }
            }
            Utils.broadcast(new OperatorApplicationEvent<>(parents, children, operator, elapsed, generation,
                    evolver, null), listeners, executor);
            return children;
        }
    };
}

From source file:appeng.crafting.CraftingJob.java

private void logCraftingJob(String type, Stopwatch timer) {
    if (AELog.isCraftingLogEnabled()) {
        final String itemToOutput = this.output.toString();
        final long elapsedTime = timer.elapsed(TimeUnit.MILLISECONDS);
        final String actionSource;

        if (this.actionSrc instanceof MachineSource) {
            final IActionHost machineSource = ((MachineSource) this.actionSrc).via;
            final IGridNode actionableNode = machineSource.getActionableNode();
            final IGridHost machine = actionableNode.getMachine();
            final DimensionalCoord location = actionableNode.getGridBlock().getLocation();

            actionSource = String.format(LOG_MACHINE_SOURCE_DETAILS, machine, location);
        } else if (this.actionSrc instanceof PlayerSource) {
            final PlayerSource source = (PlayerSource) this.actionSrc;
            final EntityPlayer player = source.player;

            actionSource = player.toString();
        } else {//from   ww  w. j a  v  a 2 s .c o m
            actionSource = "[unknown source]";
        }

        AELog.crafting(LOG_CRAFTING_JOB, type, actionSource, itemToOutput, this.bytes, elapsedTime);
    }
}

From source file:com.abiquo.apiclient.RestClient.java

public VirtualMachineDto waitUntilUnlocked(final VirtualMachineDto vm, final int pollInterval,
        final int maxWait, final TimeUnit timeUnit) {
    Stopwatch watch = Stopwatch.createStarted();
    while (watch.elapsed(timeUnit) < maxWait) {
        VirtualMachineDto refreshed = refresh(vm);
        if (!VirtualMachineState.LOCKED.equals(refreshed.getState())) {
            return refreshed;
        }//from  w w w  . j a va 2 s .  c o  m

        Uninterruptibles.sleepUninterruptibly(pollInterval, timeUnit);
    }

    throw new RuntimeException("Virtual machine did not reach the desired state in the configured timeout");
}