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.store.mongo.MongoRecordReader.java

@Override
public int next() {
    if (cursor == null) {
        logger.info("Filters Applied : " + filters);
        logger.info("Fields Selected :" + fields);
        cursor = collection.find(filters).projection(fields).batchSize(100).iterator();
    }/*from w w  w .  ja  v a  2 s.  c o  m*/

    writer.allocate();
    writer.reset();

    int docCount = 0;
    Stopwatch watch = new Stopwatch();
    watch.start();

    try {
        while (docCount < BaseValueVector.INITIAL_VALUE_ALLOCATION && cursor.hasNext()) {
            writer.setPosition(docCount);
            String doc = cursor.next().toJson();
            jsonReader.setSource(doc.getBytes(Charsets.UTF_8));
            jsonReader.write(writer);
            docCount++;
        }

        jsonReader.ensureAtLeastOneField(writer);

        writer.setValueCount(docCount);
        logger.debug("Took {} ms to get {} records", watch.elapsed(TimeUnit.MILLISECONDS), docCount);
        return docCount;
    } catch (IOException e) {
        String msg = "Failure while reading document. - Parser was at record: " + (docCount + 1);
        logger.error(msg, e);
        throw new DrillRuntimeException(msg, e);
    }
}

From source file:com.facebook.presto.split.NativeSplitManager.java

@Override
public List<Partition> getPartitions(TableHandle tableHandle, Map<ColumnHandle, Object> bindings) {
    Stopwatch partitionTimer = new Stopwatch();
    partitionTimer.start();/*from w w w  .j av a  2s  .  c  om*/

    checkArgument(tableHandle instanceof NativeTableHandle, "Table must be a native table");

    TableMetadata tableMetadata = metadata.getTableMetadata(tableHandle);

    checkState(tableMetadata != null, "no metadata for %s found", tableHandle);

    Set<TablePartition> tablePartitions = shardManager.getPartitions(tableHandle);

    log.debug("Partition retrieval, native table %s (%d partitions): %dms", tableHandle, tablePartitions.size(),
            partitionTimer.elapsed(TimeUnit.MILLISECONDS));

    Multimap<String, ? extends PartitionKey> allPartitionKeys = shardManager.getAllPartitionKeys(tableHandle);
    Map<String, ColumnHandle> columnHandles = metadata.getColumnHandles(tableHandle);

    log.debug("Partition key retrieval, native table %s (%d keys): %dms", tableHandle, allPartitionKeys.size(),
            partitionTimer.elapsed(TimeUnit.MILLISECONDS));

    List<Partition> partitions = ImmutableList.copyOf(
            Collections2.transform(tablePartitions, new PartitionFunction(columnHandles, allPartitionKeys)));

    log.debug("Partition generation, native table %s (%d partitions): %dms", tableHandle, partitions.size(),
            partitionTimer.elapsed(TimeUnit.MILLISECONDS));

    return partitions;
}

From source file:org.apache.distributedlog.client.proxy.ProxyClientManager.java

private void notifyHandshakeSuccess(SocketAddress address, ProxyClient client, ServerInfo serverInfo,
        boolean logging, Stopwatch stopwatch) {
    if (logging) {
        if (null != serverInfo && serverInfo.isSetOwnerships()) {
            logger.info("Handshaked with {} : {} ownerships returned.", address,
                    serverInfo.getOwnerships().size());
        } else {/*from w w  w. j  a  v a2 s.  c  o m*/
            logger.info("Handshaked with {} : no ownerships returned", address);
        }
    }
    handshakeStats.completeRequest(address, stopwatch.elapsed(TimeUnit.MICROSECONDS), 1);
    for (ProxyListener listener : proxyListeners) {
        listener.onHandshakeSuccess(address, client, serverInfo);
    }
}

From source file:org.apache.pulsar.functions.instance.JavaInstanceRunnable.java

private void createStateTable(String tableNs, String tableName, StorageClientSettings settings)
        throws Exception {
    try (StorageAdminClient storageAdminClient = StorageClientBuilder.newBuilder().withSettings(settings)
            .buildAdmin()) {//ww  w.ja va  2s.  co m
        StreamConfiguration streamConf = StreamConfiguration.newBuilder(DEFAULT_STREAM_CONF)
                .setInitialNumRanges(4).setMinNumRanges(4).setStorageType(StorageType.TABLE).build();
        Stopwatch elapsedWatch = Stopwatch.createStarted();
        while (elapsedWatch.elapsed(TimeUnit.MINUTES) < 1) {
            try {
                result(storageAdminClient.getStream(tableNs, tableName));
                return;
            } catch (NamespaceNotFoundException nnfe) {
                try {
                    result(storageAdminClient.createNamespace(tableNs,
                            NamespaceConfiguration.newBuilder().setDefaultStreamConf(streamConf).build()));
                    result(storageAdminClient.createStream(tableNs, tableName, streamConf));
                } catch (Exception e) {
                    // there might be two clients conflicting at creating table, so let's retrieve the table again
                    // to make sure the table is created.
                }
            } catch (StreamNotFoundException snfe) {
                try {
                    result(storageAdminClient.createStream(tableNs, tableName, streamConf));
                } catch (Exception e) {
                    // there might be two client conflicting at creating table, so let's retrieve it to make
                    // sure the table is created.
                }
            } catch (ClientException ce) {
                log.warn(
                        "Encountered issue on fetching state stable metadata, re-attempting in 100 milliseconds",
                        ce.getMessage());
                TimeUnit.MILLISECONDS.sleep(100);
            }
        }
    }
}

From source file:org.opendaylight.controller.netconf.persist.impl.ConfigPusherImpl.java

private NetconfOperationService getOperationServiceWithRetries(Set<String> expectedCapabilities,
        String idForReporting) {/*  w w w  . jav  a  2s  .  c  om*/
    Stopwatch stopwatch = Stopwatch.createStarted();
    NotEnoughCapabilitiesException lastException;
    do {
        try {
            return getOperationService(expectedCapabilities, idForReporting);
        } catch (NotEnoughCapabilitiesException e) {
            LOG.debug("Not enough capabilities: {}", e.toString());
            lastException = e;
            sleep();
        }
    } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
    throw new IllegalStateException("Max wait for capabilities reached." + lastException.getMessage(),
            lastException);
}

From source file:com.vmware.photon.controller.apife.backends.DiskSqlBackend.java

@Transactional
public void tombstone(String kind, String diskId) throws ExternalException {
    Stopwatch tombstoneWatch = Stopwatch.createStarted();

    BaseDiskEntity disk = getDiskDao(kind).findById(diskId).orNull();
    checkNotNull(disk);//from ww w .java2s .  c o  m

    String resourceTickedId = projectBackend.findById(disk.getProjectId()).getResourceTicketId();

    Stopwatch resourceTicketWatch = Stopwatch.createStarted();
    resourceTicketBackend.returnQuota(resourceTickedId, new QuotaCost(disk.getCost()));
    resourceTicketWatch.stop();
    logger.info(
            "DiskSqlBackend.tombstone for Disk Id: {}, Kind:{}, resourceTicket {}, returnQuota in {} milliseconds",
            diskId, kind, resourceTickedId, resourceTicketWatch.elapsed(TimeUnit.MILLISECONDS));

    tombstoneBackend.create(kind, disk.getId());
    getDiskDao(kind).delete(disk);
    tombstoneWatch.stop();
    logger.info("DiskSqlBackend.tombstone for Disk Id: {}, Kind:{} took {} milliseconds", diskId, kind,
            tombstoneWatch.elapsed(TimeUnit.MILLISECONDS));
}

From source file:appeng.core.AppEng.java

@EventHandler
private void postInit(final FMLPostInitializationEvent event) {
    final Stopwatch start = Stopwatch.createStarted();
    AELog.info("Post Initialization ( started )");

    this.registration.postInit(event);
    IntegrationRegistry.INSTANCE.postInit();
    FMLCommonHandler.instance().registerCrashCallable(new IntegrationCrashEnhancement());

    CommonHelper.proxy.postInit();//w  w  w  .ja  v  a  2 s.co  m
    AEConfig.instance.save();

    NetworkRegistry.INSTANCE.registerGuiHandler(this, GuiBridge.GUI_Handler);
    NetworkHandler.instance = new NetworkHandler("AE2");

    AELog.info("Post Initialization ( ended after " + start.elapsed(TimeUnit.MILLISECONDS) + "ms )");
}

From source file:com.netflix.dynomitemanager.sidecore.utils.ProcessMonitorTask.java

@Override
public void execute() throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    if (instanceState.getIsProcessMonitoringSuspended()) {
        return;// ww  w  . j a v  a 2s .  c o m
    }

    instanceState.setStorageProxyProcessAlive(checkProxyProcess());
    instanceState.setStorageProxyAlive(
            JedisUtils.isAliveWithRetry(JedisConfiguration.REDIS_ADDRESS, JedisConfiguration.DYNO_PORT));
    instanceState.setStorageAlive(iStorageProxy.isAlive());
    logger.info(String.format("ProcessMonitor state: %s, time elapsted to check (micros): %s", instanceState,
            stopwatch.elapsed(MICROSECONDS)));

    /*
    if((!instanceState.isStorageProxyAlive() && instanceState.isStorageProxyProcessAlive())) {
    if (!instanceState.isStorageAlive()) {
        logger.info("Stopping dynomite process isStorageAlive=false. Restarting dynomite will restart storage");
    }
    else {
        logger.info("Stopping hung dynomite process.");
    }
    dynProcess.stop();
    }
    */

    /*
    if (instanceState.isBootstrapping()) {
    logger.info("Instance is bootstrapping. Skipping further process checks.");
    return;
    }
            
            
    if (!instanceState.isStorageAlive()) {
    if(instanceState.isStorageProxyAlive() || instanceState.isStorageProxyProcessAlive()) {
        logger.info("Stopping Dynomite process before warm bootstrapping.");
        dynProcess.stop();
    }
            
    if (config.isWarmBootstrap()) {
        logger.info("Warm bootstraping node. Scheduling BootstrapTask now!");
        scheduler.runTaskNow(WarmBootstrapTask.class);
    }
    else {
        logger.info("Cold bootstraping, launching dynomite and storage process.");
        dynProcess.start(true);
    }
            
    logger.info(String.format("After corrective action ProcessMonitor state: %s, time elapsed to check (micros): %s",
            instanceState, stopwatch.elapsed(MICROSECONDS)));
    }
    else if(!instanceState.isStorageProxyAlive()) {
    logger.info("Launching dynomite process.");
    // starts launch dynomite script, which starts Redis if it's not already running.
    dynProcess.start(true);
            
    logger.info(String.format("After corrective action ProcessMonitor state: %s, time elapsted to check (micros): %s",
        instanceState, stopwatch.elapsed(MICROSECONDS)));
    }
    */

    stopwatch.stop();

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Time to run the check (micros): %s", stopwatch.elapsed(MICROSECONDS)));
    }
}

From source file:qa.qcri.nadeef.core.utils.RuleBuilder.java

/**
 * Generates the <code>Rule</code> class code.
 * //ww w .j  a v  a  2  s . c o  m
 * @return generated rule class.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Collection<Rule> build() throws Exception {
    List<Rule> result = Lists.newArrayList();
    Collection<File> outputFiles = compile();
    Logger tracer = Logger.getLogger(RuleBuilder.class);
    for (File outputFile : outputFiles) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        String className = Files.getNameWithoutExtension(outputFile.getName());

        URL url = new URL("file://" + outputFile.getParent() + File.separator);
        Class ruleClass = CommonTools.loadClass(className, url);
        Rule rule = (Rule) ruleClass.getConstructor().newInstance();

        rule.initialize(Files.getNameWithoutExtension(outputFile.getName()), tableNames);
        result.add(rule);
        tracer.fine("Rule file : " + outputFile.getAbsolutePath() + " is loaded in "
                + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms.");
        stopwatch.stop();
    }
    return result;
}

From source file:qa.qcri.nadeef.core.util.RuleBuilder.java

/**
 * Generates the <code>Rule</code> class code.
 * //from ww w . j a  v  a 2 s  .  com
 * @return generated rule class.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Collection<Rule> build() throws Exception {
    List<Rule> result = Lists.newArrayList();
    Collection<File> outputFiles = compile();
    Tracer tracer = Tracer.getTracer(RuleBuilder.class);
    for (File outputFile : outputFiles) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        String className = Files.getNameWithoutExtension(outputFile.getName());

        URL url = new URL("file://" + outputFile.getParent() + File.separator);
        Class ruleClass = CommonTools.loadClass(className, url);
        Rule rule = (Rule) ruleClass.getConstructor().newInstance();

        rule.initialize(Files.getNameWithoutExtension(outputFile.getName()), tableNames);
        result.add(rule);
        tracer.verbose("Rule file : " + outputFile.getAbsolutePath() + " is loaded in "
                + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms.");
        stopwatch.stop();
    }
    return result;
}