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.sonatype.sisu.bl.support.DefaultBundle.java

/**
 * Starts application and waits for it to boot. if successfully started sets the state to running.
 * <p/>//from   w w  w.j  a v a 2 s.c om
 * {@inheritDoc}
 *
 * @throws Exception if a problem occurred during startup of application, wait period or it could not determine if
 *                   application is started in specified timeout
 * @see Bundle#start()
 */
@Override
public void doStart() {
    bootingTime = Time.millis(0);
    final Stopwatch bootingWatch = Stopwatch.createUnstarted();
    try {
        startApplication();
        running = true;
        getRunningBundles().add(this);
        bootingWatch.start();
        waitForBoot();
    } catch (RuntimeException e) {
        doStop();
        throw e;
    } finally {
        if (bootingWatch.isRunning()) {
            bootingWatch.stop();
        }
        bootingTime = Time.millis(bootingWatch.elapsed(TimeUnit.MILLISECONDS));
    }
}

From source file:net.conquiris.search.AbstractSearcher.java

@Override
public CountResult getCount(final Query query, final @Nullable Filter filter, final boolean score) {
    return perform(new Op<CountResult>() {
        public CountResult perform(IndexSearcher searcher) throws Exception {
            final Stopwatch w = Stopwatch.createStarted();
            final ScoredTotalHitCountCollector scoredCollector;
            final TotalHitCountCollector collector;
            if (score) {
                scoredCollector = new ScoredTotalHitCountCollector();
                collector = scoredCollector;
            } else {
                scoredCollector = null;//w  w w. j  av a 2s .c  o m
                collector = new TotalHitCountCollector();
            }
            searcher.search(query, filter, collector);
            final float maxScore = score ? scoredCollector.getMaxScore() : 1.0f;
            return CountResult.of(collector.getTotalHits(), maxScore, w.elapsed(TimeUnit.MILLISECONDS));
        }
    });
}

From source file:com.dssmp.agent.tailing.AsyncPublisherThrottler.java

private long sleepUpTo(long delay) {
    Stopwatch timer = Stopwatch.createStarted();
    try {/*from w  ww .  j av  a2s  .c om*/
        long remaining = delay;
        while (remaining > 0) {
            if (abortBackoff) {
                LOGGER.trace("{}: Backoff was aborted.", publisher.name());
                break;
            } else {
                try {
                    Thread.sleep(SPIN_TIME_MILLIS);
                } catch (InterruptedException e) {
                    // Preserve interruption
                    Thread.currentThread().interrupt();
                    LOGGER.trace("{}: Backoff was interrupted", publisher.name(), e);
                    break;
                }
                remaining = delay - timer.elapsed(TimeUnit.MILLISECONDS);
            }
        }
    } finally {
        totalBackoffTime.addAndGet(timer.elapsed(TimeUnit.MILLISECONDS));
    }
    return timer.elapsed(TimeUnit.MILLISECONDS);
}

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

@Override
public Completable call(JobDetails jobDetails) {
    // Rewind to previous timeslice
    Stopwatch stopwatch = Stopwatch.createStarted();
    logger.info("Starting execution");
    long previousBlock = DateTimeService.getTimeSlice(
            new DateTime(jobDetails.getTrigger().getTriggerTime(), DateTimeZone.UTC).minus(DEFAULT_BLOCK_SIZE),
            DEFAULT_BLOCK_SIZE).getMillis();

    Observable<? extends MetricId<?>> metricIds = metricsService.findAllMetrics().map(Metric::getMetricId)
            .filter(m -> (m.getType() == GAUGE || m.getType() == COUNTER || m.getType() == AVAILABILITY));

    // Fetch all partition keys and compress the previous timeSlice
    return Completable.fromObservable(metricsService.compressBlock(metricIds, previousBlock)
            .doOnError(t -> logger.warn("Failed to compress data", t)).doOnCompleted(() -> {
                stopwatch.stop();/*  w  w  w.j av a 2 s.co m*/
                logger.info("Finished compressing data in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
            }));

    // TODO Optimization - new worker per token - use parallelism in Cassandra
    // Configure the amount of parallelism?
}

From source file:qa.qcri.nadeef.core.util.sql.PostgresSQLDialect.java

/**
 * {@inheritDoc}//from w  ww.ja va 2 s. c  o  m
 */
@Override
public int bulkLoad(DBConfig dbConfig, String tableName, Path file, boolean skipHeader) {
    Tracer tracer = Tracer.getTracer(PostgresSQLDialect.class);
    tracer.info("Bulk load CSV file " + file.toString());
    try (Connection conn = DBConnectionPool.createConnection(dbConfig, true);
            FileReader reader = new FileReader(file.toFile())) {
        Stopwatch watch = Stopwatch.createStarted();
        Schema schema = DBMetaDataTool.getSchema(dbConfig, tableName);
        StringBuilder builder = new StringBuilder();
        for (Column column : schema.getColumns()) {
            if (column.getColumnName().equalsIgnoreCase("TID"))
                continue;
            builder.append(column.getColumnName()).append(",");
        }
        builder.deleteCharAt(builder.length() - 1);

        CopyManager copyManager = new CopyManager((BaseConnection) conn);
        String sql = String.format("COPY %s (%s) FROM STDIN WITH (FORMAT 'csv', DELIMITER ',', HEADER %s)",
                tableName, builder.toString(), skipHeader ? "true" : "false");
        copyManager.copyIn(sql, reader);
        watch.stop();
        tracer.info("Bulk load finished in " + watch.elapsed(TimeUnit.MILLISECONDS) + " ms");
    } catch (Exception ex) {
        tracer.err("Loading csv file " + file.getFileName() + " failed.", ex);
        return 1;
    }
    return 0;
}

From source file:org.apache.hive.ptest.execution.HostExecutor.java

/**
 * Executes the test batch on the drone in question. If the command
 * exits with a status code of 255 throw an AbortDroneException.
 *//*from www .j a  v a  2  s .  co  m*/
private boolean executeTestBatch(Drone drone, TestBatch batch, Set<TestBatch> failedTestResults)
        throws IOException, SSHExecutionException, AbortDroneException {
    String scriptName = "hiveptest-" + batch.getName() + ".sh";
    File script = new File(mLocalScratchDirectory, scriptName);
    Map<String, String> templateVariables = Maps.newHashMap(mTemplateDefaults);
    templateVariables.put("instanceName", drone.getInstanceName());
    templateVariables.put("batchName", batch.getName());
    templateVariables.put("testArguments", batch.getTestArguments());
    templateVariables.put("localDir", drone.getLocalDirectory());
    templateVariables.put("logDir", drone.getLocalLogDirectory());
    Preconditions.checkArgument(StringUtils.isNotBlank(batch.getTestModuleRelativeDir()));
    templateVariables.put("testModule", batch.getTestModuleRelativeDir());
    String command = Templates.getTemplateResult("bash $localDir/$instanceName/scratch/" + script.getName(),
            templateVariables);
    Templates.writeTemplateResult("batch-exec.vm", script, templateVariables);
    copyToDroneFromLocal(drone, script.getAbsolutePath(), "$localDir/$instanceName/scratch/" + scriptName);
    script.delete();
    Stopwatch sw = Stopwatch.createStarted();
    mLogger.info(drone + " executing " + batch + " with " + command);
    RemoteCommandResult sshResult = new SSHCommand(mSSHCommandExecutor, drone.getPrivateKey(), drone.getUser(),
            drone.getHost(), drone.getInstance(), command, true).call();
    sw.stop();
    mLogger.info("Completed executing tests for batch [{}] on host {}. ElapsedTime(ms)={}",
            new Object[] { batch.getName(), getHost().toShortString(), sw.elapsed(TimeUnit.MILLISECONDS) });
    File batchLogDir = null;
    if (sshResult.getExitCode() == Constants.EXIT_CODE_UNKNOWN) {
        throw new AbortDroneException(
                "Drone " + drone.toString() + " exited with " + Constants.EXIT_CODE_UNKNOWN + ": " + sshResult);
    }
    if (mShutdown) {
        mLogger.warn("Shutting down host " + mHost.getName());
        return false;
    }
    boolean result;
    if (sshResult.getExitCode() != 0 || sshResult.getException() != null) {
        result = false;
        batchLogDir = Dirs.create(new File(mFailedTestLogDir, batch.getName()));
    } else {
        result = true;
        batchLogDir = Dirs.create(new File(mSuccessfulTestLogDir, batch.getName()));
    }
    copyFromDroneToLocal(drone, batchLogDir.getAbsolutePath(), drone.getLocalLogDirectory() + "/",
            fetchLogsForSuccessfulTests || !result);
    File logFile = new File(batchLogDir, String.format("%s.txt", batch.getName()));
    PrintWriter writer = new PrintWriter(logFile);
    writer.write(String.format("result = '%s'\n", sshResult.toString()));
    writer.write(String.format("output = '%s'\n", sshResult.getOutput()));
    if (sshResult.getException() != null) {
        sshResult.getException().printStackTrace(writer);
    }
    writer.close();
    return result;
}

From source file:com.xiaomi.linden.service.CoreLindenServiceImpl.java

@Override
public Future<Response> delete(final LindenDeleteRequest request) {
    final Stopwatch sw = Stopwatch.createStarted();
    return instanceExecutorPool.apply(new Function0<Response>() {
        @Override//from  w  w  w.  jav  a 2s .c  om
        public Response apply() {
            Response response = null;
            try {
                long eps = sw.elapsed(TimeUnit.MILLISECONDS);
                if (eps > 10) {
                    LOGGER.warn("Warning: instanceExecutorPool took " + eps + "ms to start delete.");
                    if (eps > instanceFuturePoolWaitTimeout) {
                        response = ResponseUtils.buildFailedResponse(
                                "Waiting time is too long, " + eps + "ms in instance future pool");
                        return response;
                    }
                }
                response = lindenCore.delete(request);
            } catch (Exception e) {
                String errorStackInfo = Throwables.getStackTraceAsString(e);
                response = ResponseUtils.buildFailedResponse(errorStackInfo);
            } finally {
                if (response.isSuccess()) {
                    LOGGER.info("Instance delete request succeeded, request: {}, cost: {} ms.", request,
                            sw.elapsed(TimeUnit.MILLISECONDS));
                } else {
                    LOGGER.error("Instance delete request failed, request: {}, cost: {} ms.", request,
                            sw.elapsed(TimeUnit.MILLISECONDS));
                }
                return response;
            }
        }
    });
}

From source file:com.xiaomi.linden.service.CoreLindenServiceImpl.java

@Override
public Future<Response> index(final String content) {
    final Stopwatch sw = Stopwatch.createStarted();
    return instanceExecutorPool.apply(new Function0<Response>() {
        @Override//from  w w w .  j  a v  a 2  s  .c o m
        public Response apply() {
            Response response = null;
            try {
                long eps = sw.elapsed(TimeUnit.MILLISECONDS);
                if (eps > 10) {
                    LOGGER.warn("Warning: instanceExecutorPool took " + eps + "ms to start index.");
                    if (eps > instanceFuturePoolWaitTimeout) {
                        response = ResponseUtils.buildFailedResponse(
                                "Waiting time is too long, " + eps + "ms in instance future pool");
                        return response;
                    }
                }
                LindenIndexRequest indexRequest = LindenIndexRequestParser.parse(config.getSchema(), content);
                response = lindenCore.index(indexRequest);
            } catch (Exception e) {
                String errorStackInfo = Throwables.getStackTraceAsString(e);
                response = ResponseUtils.buildFailedResponse(errorStackInfo);
            } finally {
                if (response.isSuccess()) {
                    LOGGER.info("Instance index request succeeded, content: {}, cost: {} ms.", content,
                            sw.elapsed(TimeUnit.MILLISECONDS));
                } else {
                    LOGGER.error("Instance index request failed, content: {}, cost: {} ms.", content,
                            sw.elapsed(TimeUnit.MILLISECONDS));
                }
                return response;
            }
        }
    });
}

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

public LayoutResponse getLayout(PageInstance pi, Ok result) {
    final LayoutResponse.Builder builder = LayoutResponse.builder();
    final Map<UUID, HTMLRenderer> renderers = result.getRenderers(HTMLRenderer.class,
            rc(result, pi.getLayout()));
    for (HTMLRenderer renderer : renderers.values()) {
        Iterable<CSS> csss = renderer.getCSS();
        if (csss != null) {
            for (CSS css : csss) {
                builder.addStyle(css.getUri(), css.getMedia());
            }// ww  w  .jav  a  2 s.co  m
        }
        csss = renderer.getIE6CSS();
        if (csss != null) {
            for (CSS css : csss) {
                builder.addIE6Style(css.getUri(), css.getMedia());
            }
        }
        csss = renderer.getIE7CSS();
        if (csss != null) {
            for (CSS css : csss) {
                builder.addIE7Style(css.getUri(), css.getMedia());
            }
        }
        csss = renderer.getIE8CSS();
        if (csss != null) {
            for (CSS css : csss) {
                builder.addIE8Style(css.getUri(), css.getMedia());
            }
        }
    }
    for (UUID cipId : renderers.keySet()) {
        final HTMLRenderer renderer = renderers.get(cipId);
        final HTMLFragment f = renderer.getBody();
        final Stopwatch w = Stopwatch.createStarted();
        try {
            if (f != null) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                HTML.create((Device) null).safeAdd(f).writeTo(bos, Charset.forName("UTF-8"));
                String value = new String(bos.toByteArray(), "UTF-8");
                if (value != null) {
                    builder.putMarkup(cipId, value);
                }
            }
        } catch (Exception e) {
            builder.putMarkup(cipId, "<p>Error: " + e.getMessage() + "</p>");
        } finally {
            final long t = w.elapsed(TimeUnit.MILLISECONDS);
            if (t > 150) {
                logger.warn(String.format("CIP [%s]-[%s] took [%d] ms to render in layout mode", cipId,
                        result.getCips().get(cipId).getCip().getDefinition().getType(), t));
            }
        }
    }
    return builder.get();
}

From source file:com.palantir.atlasdb.keyvalue.impl.ProfilingKeyValueService.java

@Override
public Map<Cell, Value> get(String tableName, Map<Cell, Long> timestampByCell) {
    if (log.isTraceEnabled()) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        long sizeInBytes = 0;
        Map<Cell, Value> result = delegate.get(tableName, timestampByCell);
        for (Entry<Cell, Value> entry : result.entrySet()) {
            sizeInBytes += Cells.getApproxSizeOfCell(entry.getKey()) + entry.getValue().getContents().length
                    + 4L;/*from w w w  .j  a  va2s  . c  o m*/
        }
        log.trace("Call to KVS.get on table {}, requesting {} cells took {} ms and returned {} bytes.",
                tableName, timestampByCell.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS), sizeInBytes);
        return result;
    } else {
        return delegate.get(tableName, timestampByCell);
    }
}