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:org.opendaylight.protocol.bgp.rib.impl.CheckUtil.java

public static <R, T extends DataObject> R readData(final DataBroker dataBroker, final InstanceIdentifier<T> iid,
        final Function<T, R> function) throws ReadFailedException {
    AssertionError lastError = null;
    final Stopwatch sw = Stopwatch.createStarted();
    while (sw.elapsed(TimeUnit.SECONDS) <= TIMEOUT) {
        try (final ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction()) {
            final Optional<T> data = tx.read(LogicalDatastoreType.OPERATIONAL, iid).checkedGet();
            if (data.isPresent()) {
                try {
                    return function.apply(data.get());
                } catch (final AssertionError e) {
                    lastError = e;//from   w  w  w  .  j a  v a 2  s .  com
                    Uninterruptibles.sleepUninterruptibly(SLEEP_FOR, TimeUnit.MILLISECONDS);
                }
            }
        }
    }
    Assert.fail(lastError.getMessage());
    throw lastError;
}

From source file:com.salesforce.grpc.contrib.interceptor.StopwatchServerInterceptor.java

@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
        ServerCallHandler<ReqT, RespT> next) {
    logStart(call.getMethodDescriptor());

    return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(
            next.startCall(call, headers)) {
        private Stopwatch stopwatch = Stopwatch.createStarted();

        @Override/*from   ww w .  ja va  2s . co  m*/
        public void onCancel() {
            super.onCancel();
            logCancel(call.getMethodDescriptor(),
                    Duration.ofNanos(stopwatch.stop().elapsed(TimeUnit.NANOSECONDS)));
        }

        @Override
        public void onComplete() {
            super.onComplete();
            logStop(call.getMethodDescriptor(),
                    Duration.ofNanos(stopwatch.stop().elapsed(TimeUnit.NANOSECONDS)));
        }
    };
}

From source file:eu.europa.ec.fisheries.uvms.interceptors.SimpleTracingInterceptor.java

@AroundInvoke
public Object logCall(InvocationContext context) throws Exception {

    final Stopwatch stopwatch = Stopwatch.createStarted();

    try {/*from   w  w w. j av  a 2 s  . co m*/
        log.info(String.format("invocation of method %s ", context.getMethod()));

        return context.proceed();
    } finally {
        log.info(String.format("Elapsed time ==> " + stopwatch));
    }
}

From source file:nextmethod.threading.SpinWait.java

public static boolean spinUntil(final Delegates.IFunc<Boolean> condition, final long amount,
        final TimeUnit timeUnit) {
    final SpinWait spinWait = new SpinWait();
    final Stopwatch stopwatch = Stopwatch.createStarted();

    while (!condition.invoke()) {
        if (stopwatch.elapsed(timeUnit) > amount) {
            return false;
        }//from w ww . j a va  2s  .co m
        spinWait.spinOnce();
    }
    return true;
}

From source file:fr.inria.atlanmod.neoemf.io.persistence.TimerPersistenceHandlerDecorator.java

@Override
public void processStartDocument() {
    NeoLogger.info("[{0}] Document analysis in progress...", name);
    stopWatch = Stopwatch.createStarted();

    super.processStartDocument();
}

From source file:qa.qcri.nadeef.core.pipeline.ViolationCSVExport.java

@Override
protected File execute(File file) throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    Tracer tracer = Tracer.getTracer(ViolationCSVExport.class);
    DBConfig config = getCurrentContext().getConnectionPool().getNadeefConfig();
    SQLDialectBase instance = SQLDialectFactory.getDialectManagerInstance(config.getDialect());
    tracer.info("Load " + file.getCanonicalPath() + " into violation table");
    if (instance.supportBulkLoad()) {
        instance.bulkLoad(config, "VIOLATION", file.toPath(), false);
    } else {/*w ww .j  a va 2s  .co  m*/
        instance.fallbackLoad(config, "VIOLATION", file, false);
    }

    PerfReport.appendMetric(PerfReport.Metric.ViolationExportTime, stopwatch.elapsed(TimeUnit.MILLISECONDS));
    stopwatch.stop();
    return file;
}

From source file:com.google.devtools.build.android.AndroidResourceMerger.java

/** Merges all secondary resources with the primary resources. */
public static MergedAndroidData mergeData(final ParsedAndroidData primary, final Path primaryManifest,
        final List<? extends SerializedAndroidData> direct,
        final List<? extends SerializedAndroidData> transitive, final Path resourcesOut, final Path assetsOut,
        @Nullable final PngCruncher cruncher, final VariantType type, @Nullable final Path symbolsOut,
        @Nullable AndroidResourceClassWriter rclassWriter, AndroidDataDeserializer deserializer)
        throws MergingException {
    Stopwatch timer = Stopwatch.createStarted();
    final ListeningExecutorService executorService = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(15));
    try (Closeable closeable = ExecutorServiceCloser.createWith(executorService)) {
        AndroidDataMerger merger = AndroidDataMerger.createWithPathDeduplictor(executorService, deserializer);
        UnwrittenMergedAndroidData merged = mergeData(executorService, transitive, direct, primary,
                primaryManifest, type != VariantType.LIBRARY, deserializer);
        timer.reset().start();// ww w.  j a  v a 2 s  .  com
        if (symbolsOut != null) {
            AndroidDataSerializer serializer = AndroidDataSerializer.create();
            merged.serializeTo(serializer);
            serializer.flushTo(symbolsOut);
            logger.fine(
                    String.format("serialize merge finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
            timer.reset().start();
        }
        if (rclassWriter != null) {
            merged.writeResourceClass(rclassWriter);
            logger.fine(String.format("write classes finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
            timer.reset().start();
        }
        AndroidDataWriter writer = AndroidDataWriter.createWith(resourcesOut.getParent(), resourcesOut,
                assetsOut, cruncher, executorService);
        return merged.write(writer);
    } catch (IOException e) {
        throw MergingException.wrapException(e).build();
    } finally {
        logger.fine(String.format("write merge finished in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
    }
}

From source file:org.apache.jackrabbit.oak.backup.FileStoreRestore.java

public static void restore(File source, File destination) throws IOException {
    if (!validFileStore(source)) {
        throw new IOException("Folder " + source + " is not a valid FileStore directory");
    }//w w w . j  a  v a 2  s .  c o m

    FileStore restore = fileStoreBuilder(source).buildReadOnly();
    Stopwatch watch = Stopwatch.createStarted();

    FileStore store = fileStoreBuilder(destination).build();
    SegmentNodeState current = store.getHead();
    try {
        SegmentNodeState head = restore.getHead();
        int gen = head.getRecordId().getSegment().getGcGeneration();
        SegmentBufferWriter bufferWriter = new SegmentBufferWriter(store, store.getTracker(), store.getReader(),
                "r", gen);
        SegmentWriter writer = new SegmentWriter(store, store.getReader(), store.getBlobStore(),
                new WriterCacheManager.Default(), bufferWriter);
        SegmentGCOptions gcOptions = defaultGCOptions().setOffline();
        Compactor compactor = new Compactor(store.getReader(), writer, store.getBlobStore(),
                Suppliers.ofInstance(false), gcOptions);
        compactor.setContentEqualityCheck(true);
        SegmentNodeState after = compactor.compact(current, head, current);
        store.getRevisions().setHead(current.getRecordId(), after.getRecordId());
    } finally {
        restore.close();
        store.close();
    }
    watch.stop();
    log.info("Restore finished in {}.", watch);
}

From source file:eu.europa.ec.fisheries.uvms.interceptors.TracingInterceptor.java

@AroundInvoke
public Object logCall(InvocationContext context) throws Exception {

    final Stopwatch stopwatch = Stopwatch.createStarted();

    try {//from w  w  w  .  ja  v  a2 s.co m

        Object[] parameters = context.getParameters();
        String params = "";
        for (Object parameter : parameters) {
            params += " " + String.valueOf(parameter);
        }

        log.debug(String.format("invocation of method %s with parameters %s", context.getMethod(), params));

        return context.proceed();

    } finally {
        log.info(String.format("Elapsed time ==> " + stopwatch));
    }
}

From source file:me.bramhaag.discordselfbot.commands.admin.CommandPing.java

@Command(name = "ping")
public void execute(@NonNull Message message, @NonNull TextChannel channel, @NonNull String[] args) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    message.editMessage("`Waiting...`").queue(m -> {
        stopwatch.stop();//from w ww .  j  a  v a2  s  .co  m
        m.editMessage(new EmbedBuilder().setTitle(Constants.PONG_EMOTE + " Pong!", null)
                .addField("Response time (Bot)", stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms", true)
                .addField("Response time (API)", message.getJDA().getPing() + " ms", true)
                .setFooter("Ping | " + Util.generateTimestamp(), null).build())
                .queue(embed -> embed.delete().queueAfter(Constants.REMOVE_TIME_LONG, TimeUnit.SECONDS));
    });
}