List of usage examples for com.google.common.base Stopwatch elapsed
@CheckReturnValue public long elapsed(TimeUnit desiredUnit)
From source file:org.apache.drill.exec.store.parquet.columnreaders.AsyncPageReader.java
@Override protected void nextInternal() throws IOException { ReadStatus readStatus = null;// ww w . j a va 2s. c o m try { Stopwatch timer = Stopwatch.createStarted(); readStatus = asyncPageRead.get(); long timeBlocked = timer.elapsed(TimeUnit.NANOSECONDS); stats.timeDiskScanWait.addAndGet(timeBlocked); stats.timeDiskScan.addAndGet(readStatus.getDiskScanTime()); if (readStatus.isDictionaryPage) { stats.numDictPageLoads.incrementAndGet(); stats.timeDictPageLoads.addAndGet(timeBlocked + readStatus.getDiskScanTime()); } else { stats.numDataPageLoads.incrementAndGet(); stats.timeDataPageLoads.addAndGet(timeBlocked + readStatus.getDiskScanTime()); } pageHeader = readStatus.getPageHeader(); // reset this. At the time of calling close, if this is not null then a pending asyncPageRead needs to be consumed asyncPageRead = null; } catch (Exception e) { handleAndThrowException(e, "Error reading page data."); } // TODO - figure out if we need multiple dictionary pages, I believe it may be limited to one // I think we are clobbering parts of the dictionary if there can be multiple pages of dictionary do { if (pageHeader.getType() == PageType.DICTIONARY_PAGE) { readDictionaryPageData(readStatus, parentColumnReader); // Ugly. Use the Async task to make a synchronous read call. readStatus = new AsyncPageReaderTask().call(); pageHeader = readStatus.getPageHeader(); } } while (pageHeader.getType() == PageType.DICTIONARY_PAGE); if (parentColumnReader.totalValuesRead + readStatus.getValuesRead() < parentColumnReader.columnChunkMetaData .getValueCount()) { asyncPageRead = threadPool.submit(new AsyncPageReaderTask()); } pageHeader = readStatus.getPageHeader(); pageData = getDecompressedPageData(readStatus); }
From source file:org.hawkular.metrics.core.jobs.TempDataCompressor.java
@Override public Completable call(JobDetails jobDetails) { Duration runtimeBlockSize = Duration.standardHours(2); Trigger trigger = jobDetails.getTrigger(); DateTime timeSliceInclusive = new DateTime(trigger.getTriggerTime(), DateTimeZone.UTC) .minus(runtimeBlockSize);// w w w. j a v a2 s. com // Rewind to previous timeslice DateTime timeSliceStart = DateTimeService.getTimeSlice(timeSliceInclusive, runtimeBlockSize); long startOfSlice = timeSliceStart.getMillis(); Stopwatch stopwatch = Stopwatch.createStarted(); logger.infof("Starting to process temp table for starting time of %s", timeSliceStart.toString()); // TODO Optimization - new worker per token - use parallelism in Cassandra (with configured parallelism) return metricsService.compressBlock(startOfSlice, pageSize, maxReadConcurrency).doOnCompleted(() -> { stopwatch.stop(); logger.info("Finished processing data in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms"); }); }
From source file:com.thinkbiganalytics.metadata.jpa.cache.ClusterAwareDtoCache.java
private void refresh() { try {//from w w w . j a v a2s . c o m log.info("Populating Cache for {} ", getProviderName()); Stopwatch stopwatch = Stopwatch.createStarted(); List<E> entities = fetchAll(); entities.stream().map(entity -> transformEntityToDto(entity)).forEach(dto -> addItem(dto)); populatedCache.set(true); stopwatch.stop(); log.info("Time to populate {} Cache {}", getProviderName(), stopwatch.elapsed(TimeUnit.MILLISECONDS)); } catch (Exception e) { populatedCache.set(false); } populatingCache.set(false); }
From source file:com.thinkbiganalytics.metadata.jpa.cache.AbstractCacheBackedProvider.java
private void refresh() { try {//from w ww . j a v a 2 s . c om log.info("Populating Cache for {} ", getProviderName()); Stopwatch stopwatch = Stopwatch.createStarted(); addItems(repository.findAll()); populatedCache.set(true); cacheListeners.stream().forEach(CacheBackedProviderListener::onPopulated); stopwatch.stop(); log.info("Time to populate {} Cache {}", getProviderName(), stopwatch.elapsed(TimeUnit.MILLISECONDS)); } catch (Exception e) { populatedCache.set(false); } populatingCache.set(false); }
From source file:eu.project.ttc.models.occstore.MongoDBOccurrenceStore.java
@Override public void deleteMany(TermSelector selector) { if (selector instanceof FrequencyUnderThreshholdSelector) { FrequencyUnderThreshholdSelector selector2 = (FrequencyUnderThreshholdSelector) selector; sync();/*from w w w . j a va 2s .c o m*/ Stopwatch sw = Stopwatch.createStarted(); termCollection.deleteMany(Filters.lt(FREQUENCY, selector2.getThreshhold())); LOGGER.debug("Terms deleted in MongoDB in {}ms", sw.elapsed(TimeUnit.MILLISECONDS)); } }
From source file:com.minestellar.core.MinestellarCore.java
@EventHandler public void preInit(FMLPreInitializationEvent event) { Stopwatch stopwatch = Stopwatch.createStarted(); new ConfigManagerCore(new File(event.getModConfigurationDirectory(), "Minestellar/blocks.cfg")); CoreBlocks.init();//from www. jav a2 s. c o m CoreItems.init(); GameRegistry.registerBlock(new TestDataBlock("testDataBlock"), "testDataBlock"); MinestellarCore.proxy.preInit(event); log.info("PreInitialization Completed in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms."); }
From source file:org.jclouds.virtualbox.functions.CreateAndInstallVm.java
@Override public IMachine apply(MasterSpec masterSpec) { VmSpec vmSpec = masterSpec.getVmSpec(); IsoSpec isoSpec = masterSpec.getIsoSpec(); String masterName = vmSpec.getVmName(); IMachine masterMachine = checkNotNull(createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(masterSpec), "master machine"); // Launch machine and wait for it to come online machineController.ensureMachineIsLaunched(masterName); String installationKeySequence = isoSpec.getInstallationKeySequence().replace("PRECONFIGURATION_URL", preconfigurationUrl);/*from ww w . j a v a2 s . com*/ configureOsInstallationWithKeyboardSequence(masterName, installationKeySequence); masterMachine.setExtraData(GUEST_OS_USER, masterSpec.getLoginCredentials().getUser()); masterMachine.setExtraData(GUEST_OS_PASSWORD, masterSpec.getLoginCredentials().getPassword()); SshClient client = sshClientForIMachine.apply(masterMachine); logger.debug(">> awaiting installation to finish node(%s)", masterName); Stopwatch stopwatch = Stopwatch.createUnstarted(); stopwatch.start(); checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", masterName); stopwatch.stop(); logger.debug(String.format("Elapsed time for the OS installation: %d minutes", TimeUnit.SECONDS.convert(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS))); NodeMetadata nodeMetadata = imachineToNodeMetadata.apply(masterMachine); logger.debug(">> awaiting post-installation actions on vm: %s", masterName); ListenableFuture<ExecResponse> execCleanup = machineUtils.runScriptOnNode(nodeMetadata, call("cleanupUdevIfNeeded"), RunScriptOptions.NONE); ExecResponse cleanupResponse = Futures.getUnchecked(execCleanup); checkState(cleanupResponse.getExitStatus() == 0, "post-installation actions on vm(%s) failed", masterName); logger.debug(">> awaiting installation of guest additions on vm: %s", masterName); ListenableFuture<ExecResponse> execInstallGA = machineUtils.runScriptOnNode(nodeMetadata, new InstallGuestAdditions(vmSpec, version), RunScriptOptions.NONE); logger.debug(">> check installation of guest additions on vm: %s", masterName); ListenableFuture<ExecResponse> checkGAinstallation = machineUtils.runScriptOnNode(nodeMetadata, call("checkVBoxService"), RunScriptOptions.NONE); ExecResponse checkGAinstallationResponse = Futures.getUnchecked(checkGAinstallation); checkState(checkGAinstallationResponse.getExitStatus() == 0, "check installation of guest additions on vm(%s) " + "failed", masterName); machineController.ensureMachineIsShutdown(masterName); // detach DVD and ISOs, if needed Iterable<IMediumAttachment> mediumAttachments = Iterables.filter( masterMachine.getMediumAttachmentsOfController("IDE Controller"), new Predicate<IMediumAttachment>() { public boolean apply(IMediumAttachment in) { return in.getMedium() != null && in.getMedium().getDeviceType().equals(DeviceType.DVD); } }); for (IMediumAttachment iMediumAttachment : mediumAttachments) { logger.debug("<< iMedium(%s) detached from (%s)", iMediumAttachment.getMedium().getName(), masterMachine.getName()); machineUtils.sharedLockMachineAndApply(masterMachine.getName(), new DetachDistroMediumFromMachine( iMediumAttachment.getController(), iMediumAttachment.getPort(), iMediumAttachment.getDevice())); } return masterMachine; }
From source file:com.github.ibole.microservice.security.auth.jwt.jose4j.EcJose4jTokenAuthenticator.java
@Override public String renewAccessToken(String refreshToken, int ttlSeconds) throws TokenHandlingException { Preconditions.checkArgument(!Strings.isNullOrEmpty(refreshToken), "Token cannot be null"); final Stopwatch stopwatch = Stopwatch.createStarted(); String newToken;/* www . ja v a 2 s.co m*/ JwtObject jwtObj = JoseUtils.claimsOfTokenWithoutValidation(refreshToken); jwtObj.setTtlSeconds(ttlSeconds); newToken = createAccessToken(jwtObj); String elapsedString = Long.toString(stopwatch.elapsed(TimeUnit.MILLISECONDS)); logger.debug("Renew token elapsed time: {} ms", elapsedString); return newToken; }
From source file:com.google.pubsub.clients.common.Task.java
@Override public void run() { try {/*from w w w. j a va 2 s . c om*/ if (!outstandingRequestLimiter.tryAcquire(250, TimeUnit.MILLISECONDS)) { return; } } catch (InterruptedException e) { return; } if (!rateLimiter.tryAcquire(250, TimeUnit.MILLISECONDS)) { outstandingRequestLimiter.release(); return; } Stopwatch stopwatch = Stopwatch.createStarted(); Futures.addCallback(doRun(), new FutureCallback<RunResult>() { @Override public void onSuccess(RunResult result) { stopwatch.stop(); outstandingRequestLimiter.release(); if (result.batchSize > 0) { recordBatchLatency(stopwatch.elapsed(TimeUnit.MILLISECONDS), result.batchSize); return; } if (result.identifiers.isEmpty()) { // Because result.identifiers is not populated, we are not checking for // duplicates, so just record the latencies immediately. result.latencies.forEach(l -> recordLatency(l)); return; } recordAllMessageLatencies(result.identifiers, result.latencies); } @Override public void onFailure(Throwable t) { outstandingRequestLimiter.release(); } }); }
From source file:com.facebook.buck.distributed.DistributedBuild.java
public int executeAndPrintFailuresToEventBus(final WeightedListeningExecutorService executorService, BuckEventBus eventBus) throws IOException, InterruptedException { BuildJob job = distBuildService.createBuild(); final BuildId id = job.getBuildId(); LOG.info("Created job. Build id = " + id.getId()); logDebugInfo(job);/*from w w w. jav a 2s .co m*/ try { distBuildService.uploadMissingFiles(buildJobState.fileHashes, executorService).get(); } catch (ExecutionException e) { LOG.error("Exception uploading local changes: " + e); throw new RuntimeException(e); } LOG.info("Uploaded local changes. Build status: " + job.getStatus().toString()); try { distBuildService.uploadTargetGraph(buildJobState, id, executorService).get(); } catch (ExecutionException e) { LOG.error("Exception uploading build graph: " + e); throw new RuntimeException(e); } LOG.info("Uploaded target graph. Build status: " + job.getStatus().toString()); distBuildService.setBuckVersion(id, buckVersion); LOG.info("Set Buck Version. Build status: " + job.getStatus().toString()); job = distBuildService.startBuild(id); LOG.info("Started job. Build status: " + job.getStatus().toString()); logDebugInfo(job); Stopwatch stopwatch = Stopwatch.createStarted(); // Keep polling until the build is complete or failed. do { job = distBuildService.getCurrentBuildJobState(id); LOG.info("Got build status: " + job.getStatus().toString()); DistBuildStatus distBuildStatus = prepareStatusFromJob(job) .setETAMillis(MAX_BUILD_DURATION_MILLIS - stopwatch.elapsed(TimeUnit.MILLISECONDS)).build(); eventBus.post(new DistBuildStatusEvent(distBuildStatus)); try { // TODO(shivanker): Get rid of sleeps in methods which we want to unit test Thread.sleep(millisBetweenStatusPoll); } catch (InterruptedException e) { LOG.error(e, "BuildStatus polling sleep call has been interrupted unexpectedly."); } } while (!(job.getStatus().equals(BuildStatus.FINISHED_SUCCESSFULLY) || job.getStatus().equals(BuildStatus.FAILED))); LOG.info("Build was " + (job.getStatus().equals(BuildStatus.FINISHED_SUCCESSFULLY) ? "" : "not ") + "successful!"); logDebugInfo(job); DistBuildStatus distBuildStatus = prepareStatusFromJob(job).setETAMillis(0).build(); eventBus.post(new DistBuildStatusEvent(distBuildStatus)); return job.getStatus().equals(BuildStatus.FINISHED_SUCCESSFULLY) ? 0 : 1; }