List of usage examples for com.google.common.base Stopwatch stop
public Stopwatch stop()
From source file:com.smithsmodding.smithscore.SmithsCore.java
@Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { Stopwatch watch = Stopwatch.createStarted(); if (isInDevenvironment()) { getLogger().warn(CoreReferences.LogMarkers.PREINIT, ""); getLogger().warn(CoreReferences.LogMarkers.PREINIT, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); getLogger().warn(CoreReferences.LogMarkers.PREINIT, "SmithsCore starting in Dev mode. Current active Features:"); getLogger().warn(CoreReferences.LogMarkers.PREINIT, " > Additional log output."); getLogger().warn(CoreReferences.LogMarkers.PREINIT, " > Debug rendering of structures."); getLogger().warn(CoreReferences.LogMarkers.PREINIT, " > Debug overlay rendering of UI components,"); getLogger().warn(CoreReferences.LogMarkers.PREINIT, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); getLogger().warn(CoreReferences.LogMarkers.PREINIT, ""); } else {/*from w w w . j a v a 2s. c om*/ getLogger().info(CoreReferences.LogMarkers.PREINIT, "SmithsCore starting in Normal mode."); } proxy.preInit(); watch.stop(); Long milliseconds = watch.elapsed(TimeUnit.MILLISECONDS); getLogger().info(CoreReferences.LogMarkers.PREINIT, "SmithsCore Pre-Init completed after: " + milliseconds + " mS."); }
From source file:com.vmware.photon.controller.apife.backends.VmXenonBackend.java
@Override public void tombstone(VmEntity vm) throws ExternalException { Stopwatch tombstoneWatch = Stopwatch.createStarted(); String resourceTickedId = projectBackend.findById(vm.getProjectId()).getResourceTicketId(); ImageEntity image = null;//from www. j ava2s .c om if (StringUtils.isNotBlank(vm.getImageId())) { image = imageBackend.findById(vm.getImageId()); } FlavorEntity flavor = null; if (StringUtils.isNotBlank(vm.getFlavorId())) { flavor = flavorBackend.getEntityById(vm.getFlavorId()); } List<NetworkEntity> networkList = new LinkedList<>(); // Temporarily disable tombstoning networks when vm is being deleted if (!useVirtualNetwork) { if (null != vm.getNetworks()) { for (String network : vm.getNetworks()) { networkList.add(networkBackend.findById(network)); } } } Stopwatch resourceTicketWatch = Stopwatch.createStarted(); resourceTicketBackend.returnQuota(resourceTickedId, new QuotaCost(vm.getCost())); resourceTicketWatch.stop(); logger.info("VmXenonBackend.tombstone for Vm Id: {}, resourceTicket {}, returnQuota in {} milliseconds", vm.getId(), resourceTickedId, resourceTicketWatch.elapsed(TimeUnit.MILLISECONDS)); tombstoneBackend.create(Vm.KIND, vm.getId()); xenonClient.delete(VmServiceFactory.SELF_LINK + "/" + vm.getId(), new VmService.State()); for (AttachedDiskEntity attachedDisk : attachedDiskBackend.findByVmId(vm.getId())) { attachedDiskBackend.deleteAttachedDiskById(attachedDisk.getId()); } if (image != null && ImageState.PENDING_DELETE.equals(image.getState())) { imageBackend.tombstone(image); } if (flavor != null && FlavorState.PENDING_DELETE.equals(flavor.getState())) { flavorBackend.tombstone(flavor); } for (NetworkEntity network : networkList) { if (SubnetState.PENDING_DELETE.equals(network.getState())) { networkBackend.tombstone(network); } } tombstoneWatch.stop(); logger.info("VmXenonBackend.tombstone for Vm Id: {} took {} milliseconds", vm.getId(), tombstoneWatch.elapsed(TimeUnit.MILLISECONDS)); }
From source file:benchmarkio.consumer.activemq.ActiveMQMessageConsumer.java
@Override public Histogram call() throws Exception { int messageCount = 0; try {// w w w. j a va 2s.c om // Note that this is a polling consumer and will be terminated // whenever the Consts.POLLING_CONSUMER_MAX_IDLE_TIME_MS passes and no new messages have arrived. while (true) { // Start final Stopwatch stopwatch = Stopwatch.createStarted(); // Wait for a message // This is hilarious, according to the implementation javadoc comment: // Will return the next message produced for this message consumer, or null if // the timeout expires or this message consumer is concurrently closed final Message message = consumer.receive(Consts.POLLING_CONSUMER_MAX_IDLE_TIME_MS); if (message == null) { break; } messageCount++; // if (message instanceof TextMessage) { // final TextMessage textMessage = (TextMessage) message; // final String text = textMessage.getText(); // System.out.println("Received: " + text); // } else { // System.out.println("Received: " + message); // } // End stopwatch.stop(); histogram.recordValue(stopwatch.elapsed(Consts.TIME_UNIT_FOR_REPORTING)); } } catch (final Exception e) { // This is by purpose, hence no error logging. logger.info("Consumer was terminated through timeout"); } logger.info("In total consumed {} messages", messageCount); return histogram; }
From source file:com.vmware.photon.controller.apife.backends.VmXenonBackend.java
private VmEntity create(ProjectEntity project, VmCreateSpec spec) throws ExternalException { Stopwatch createWatch = Stopwatch.createStarted(); FlavorEntity flavorEntity = flavorBackend.getEntityByNameAndKind(spec.getFlavor(), Vm.KIND); if (!FlavorState.READY.equals(flavorEntity.getState())) { throw new InvalidFlavorStateException( String.format("Create vm using flavor with name: %s is in invalid state %s.", flavorEntity.getName(), flavorEntity.getState())); }//from ww w . ja v a 2 s.c o m VmService.State vm = new VmService.State(); vm.name = spec.getName(); vm.flavorId = flavorEntity.getId(); List<QuotaLineItemEntity> cost = new ArrayList<>(flavorEntity.getCost()); for (QuotaLineItemEntity quotaLineItemEntity : cost) { QuotaLineItem quotaLineItem = new QuotaLineItem(); quotaLineItem.setKey(quotaLineItemEntity.getKey()); quotaLineItem.setValue(quotaLineItemEntity.getValue()); quotaLineItem.setUnit(quotaLineItemEntity.getUnit()); if (vm.cost == null) { vm.cost = new ArrayList<>(); } vm.cost.add(quotaLineItem); } vm.tags = new HashSet<>(); if (spec.getTags() != null) { for (String tagText : spec.getTags()) { vm.tags.add(tagText); } } vm.networks = spec.getSubnets(); ImageEntity image = imageBackend.findById(spec.getSourceImageId()); if (!ImageState.READY.equals(image.getState())) { throw new InvalidImageStateException( String.format("Image %s is in %s state", image.getId(), image.getState())); } vm.imageId = image.getId(); List<Throwable> warnings = new ArrayList<>(); updateBootDiskCapacity(spec.getAttachedDisks(), image, warnings); vm.projectId = project.getId(); vm.vmState = VmState.CREATING; String resourceTickedId = project.getResourceTicketId(); Stopwatch resourceTicketWatch = Stopwatch.createStarted(); resourceTicketBackend.consumeQuota(resourceTickedId, new QuotaCost(cost)); resourceTicketWatch.stop(); logger.info("VmXenonBackend.create for Vm Name: {}, resourceTicket {}, consumeQuota in {} milliseconds", vm.name, resourceTickedId, resourceTicketWatch.elapsed(TimeUnit.MILLISECONDS)); vm.affinities = spec.getAffinities(); com.vmware.xenon.common.Operation createOperation = xenonClient.post(VmServiceFactory.SELF_LINK, vm); VmService.State createdVm = createOperation.getBody(VmService.State.class); VmEntity vmEntity = toVmEntity(createdVm); //set transient properties of vm entity vmEntity.setAttachedDisks(attachedDiskBackend.createAttachedDisks(vmEntity, spec.getAttachedDisks())); vmEntity.setWarnings(warnings); vmEntity.setEnvironment(spec.getEnvironment()); createWatch.stop(); logger.info("VmXenonBackend.create for Vm Id: {} and name: {} took {} milliseconds", vmEntity.getId(), vm.name, createWatch.elapsed(TimeUnit.MILLISECONDS)); return vmEntity; }
From source file:org.libdohj.params.AbstractNamecoinParams.java
@Override public void checkDifficultyTransitions(StoredBlock storedPrev, Block nextBlock, BlockStore blockStore) throws VerificationException, BlockStoreException { // This is copied verbatim from Bitcoin except for the Namecoin changes marked accordingly Block prev = storedPrev.getHeader(); // Is this supposed to be a difficulty transition point? if (!isDifficultyTransitionPoint(storedPrev)) { // No ... so check the difficulty didn't actually change. if (nextBlock.getDifficultyTarget() != prev.getDifficultyTarget()) throw new VerificationException("Unexpected change in difficulty at height " + storedPrev.getHeight() + ": " + Long.toHexString(nextBlock.getDifficultyTarget()) + " vs " + Long.toHexString(prev.getDifficultyTarget())); return;/*w ww . java 2s. co m*/ } // We need to find a block far back in the chain. It's OK that this is expensive because it only occurs every // two weeks after the initial block chain download. final Stopwatch watch = Stopwatch.createStarted(); StoredBlock cursor = blockStore.get(prev.getHash()); // Namecoin addition int blocksBack = this.getInterval() - 1; if (storedPrev.getHeight() >= this.getAuxpowStartHeight() && (storedPrev.getHeight() + 1 > this.getInterval())) { blocksBack = this.getInterval(); } // Namecoin modification //for (int i = 0; i < this.getInterval() - 1; i++) { for (int i = 0; i < blocksBack; i++) { if (cursor == null) { // This should never happen. If it does, it means we are following an incorrect or busted chain. throw new VerificationException( "Difficulty transition point but we did not find a way back to the genesis block."); } cursor = blockStore.get(cursor.getHeader().getPrevBlockHash()); } watch.stop(); if (watch.elapsed(TimeUnit.MILLISECONDS) > 50) log.info("Difficulty transition traversal took {}", watch); Block blockIntervalAgo = cursor.getHeader(); int timespan = (int) (prev.getTimeSeconds() - blockIntervalAgo.getTimeSeconds()); // Limit the adjustment step. final int targetTimespan = this.getTargetTimespan(); if (timespan < targetTimespan / 4) timespan = targetTimespan / 4; if (timespan > targetTimespan * 4) timespan = targetTimespan * 4; BigInteger newTarget = Utils.decodeCompactBits(prev.getDifficultyTarget()); newTarget = newTarget.multiply(BigInteger.valueOf(timespan)); newTarget = newTarget.divide(BigInteger.valueOf(targetTimespan)); if (newTarget.compareTo(this.getMaxTarget()) > 0) { log.info("Difficulty hit proof of work limit: {}", newTarget.toString(16)); newTarget = this.getMaxTarget(); } int accuracyBytes = (int) (nextBlock.getDifficultyTarget() >>> 24) - 3; long receivedTargetCompact = nextBlock.getDifficultyTarget(); // The calculated difficulty is to a higher precision than received, so reduce here. BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8); newTarget = newTarget.and(mask); long newTargetCompact = Utils.encodeCompactBits(newTarget); if (newTargetCompact != receivedTargetCompact) throw new VerificationException("Network provided difficulty bits do not match what was calculated: " + Long.toHexString(newTargetCompact) + " vs " + Long.toHexString(receivedTargetCompact)); }
From source file:io.dropwizard.revolver.core.RevolverCommand.java
@SuppressWarnings("unchecked") public CompletableFuture<ResponseType> executeAsync(final RequestType request) { final RequestType normalizedRequest = RevolverCommandHelper.normalize(request); final TraceInfo traceInfo = normalizedRequest.getTrace(); addContextInfo(request, traceInfo);//from ww w .j a v a 2 s .c o m final Stopwatch watch = Stopwatch.createStarted(); final Future<ResponseType> responseFuture = new RevolverCommandHandler( RevolverCommandHelper.setter(this, request.getApi()), this.context, this, normalizedRequest) .queue(); return CompletableFuture.supplyAsync(() -> { String errorMessage = null; try { return responseFuture.get(); } catch (Throwable t) { errorMessage = RevolverExceptionHelper.getLeafErrorMessage(t); throw new RevolverExecutionException(RevolverExecutionException.Type.SERVICE_ERROR, String.format("Error executing command %s", RevolverCommandHelper.getName(request)), RevolverExceptionHelper.getLeafThrowable(t)); } finally { publishTrace(Trace.builder().caller(this.clientConfiguration.getClientName()) .service(this.serviceConfiguration.getService()).api(request.getApi()) .duration(watch.stop().elapsed(TimeUnit.MILLISECONDS)) .transactionId(traceInfo.getTransactionId()).requestId(traceInfo.getRequestId()) .parentRequestId(traceInfo.getParentRequestId()).timestamp(traceInfo.getTimestamp()) .attributes(traceInfo.getAttributes()).error(!Strings.isNullOrEmpty(errorMessage)) .errorReason(errorMessage).build()); removeContextInfo(); } }); }
From source file:org.sleuthkit.autopsy.timeline.events.db.EventDB.java
/** * count all the events with the given options and return a map organizing * the counts in a hierarchy from date > eventtype> count * * * @param startTime events before this time will be excluded (seconds from * unix epoch)//from w w w . j a va 2s.co m * @param endTime events at or after this time will be excluded (seconds * from unix epoch) * @param filter only events that pass this filter will be counted * @param zoomLevel only events of this type or a subtype will be counted * and the counts will be organized into bins for each of the subtypes of * the given event type * * @return a map organizing the counts in a hierarchy from date > eventtype> * count */ private Map<EventType, Long> countEvents(Long startTime, Long endTime, Filter filter, EventTypeZoomLevel zoomLevel) { if (Objects.equals(startTime, endTime)) { endTime++; } Map<EventType, Long> typeMap = new HashMap<>(); //do we want the root or subtype column of the databse final boolean useSubTypes = (zoomLevel == EventTypeZoomLevel.SUB_TYPE); //get some info about the range of dates requested final String queryString = "select count(*), " + (useSubTypes ? SUB_TYPE_COLUMN : BASE_TYPE_COLUMN) // NON-NLS + " from events where time >= " + startTime + " and time < " + endTime + " and " + getSQLWhere(filter) // NON-NLS + " GROUP BY " + (useSubTypes ? SUB_TYPE_COLUMN : BASE_TYPE_COLUMN); // NON-NLS ResultSet rs = null; dbReadLock(); //System.out.println(queryString); try (Statement stmt = con.createStatement();) { Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); rs = stmt.executeQuery(queryString); stopwatch.stop(); // System.out.println(stopwatch.elapsedMillis() / 1000.0 + " seconds"); while (rs.next()) { EventType type = useSubTypes ? RootEventType.allTypes.get(rs.getInt(SUB_TYPE_COLUMN)) : BaseTypes.values()[rs.getInt(BASE_TYPE_COLUMN)]; typeMap.put(type, rs.getLong("count(*)")); // NON-NLS } } catch (Exception ex) { LOGGER.log(Level.SEVERE, "error getting count of events from db.", ex); // NON-NLS } finally { try { rs.close(); } catch (SQLException ex) { Exceptions.printStackTrace(ex); } dbReadUnlock(); } return typeMap; }
From source file:org.n52.youngs.control.impl.SingleThreadBulkRunner.java
@Override public Report load(final Sink sink) { this.sink = sink; Objects.nonNull(source);// www . java 2 s. com Objects.nonNull(mapper); Objects.nonNull(this.sink); log.info("Starting harvest from {} to {} with {}", source, this.sink, mapper); Report report = new ReportImpl(); try { boolean prepareSink = sink.prepare(mapper.getMapper()); if (!prepareSink) { String msg = "The sink could not be prepared. Stopping load, please check the logs."; log.error(msg); report.addMessage(msg); return report; } } catch (SinkError e) { log.error("Problem preparing sink", e); report.addMessage(String.format("Problem preparing sink: %s", e.getMessage())); return report; } final Stopwatch timer = Stopwatch.createStarted(); long pageStart = startPosition; long count = source.getRecordCount(); final long limit = Math.min(recordsLimit + startPosition, count); final Stopwatch sourceTimer = Stopwatch.createUnstarted(); final Stopwatch mappingTimer = Stopwatch.createUnstarted(); final Stopwatch sinkTimer = Stopwatch.createUnstarted(); final Stopwatch currentBulkTimer = Stopwatch.createUnstarted(); double bulkTimeAvg = 0d; long runNumber = 0; while (pageStart <= limit) { currentBulkTimer.start(); long recordsLeft = limit - pageStart + 1; long size = Math.min(recordsLeft, bulkSize); if (size <= 0) { break; } log.info("### [{}] Requesting {} records from {} starting at {}, last requested record will be {} ###", runNumber, size, source.getEndpoint(), pageStart, limit); try { sourceTimer.start(); Collection<SourceRecord> records = source.getRecords(pageStart, size, report); sourceTimer.stop(); log.debug("Mapping {} retrieved records.", records.size()); mappingTimer.start(); List<SinkRecord> mappedRecords = records.stream().map(record -> { try { return mapper.map(record); } catch (MappingError e) { report.addFailedRecord(record.toString(), "Problem during mapping: " + e.getMessage()); return null; } }).filter(Objects::nonNull).collect(Collectors.toList()); mappingTimer.stop(); log.debug("Storing {} mapped records.", mappedRecords.size()); if (!testRun) { sinkTimer.start(); mappedRecords.forEach(record -> { try { boolean result = sink.store(record); if (result) { report.addSuccessfulRecord(record.getId()); } else { report.addFailedRecord(record.getId(), "see sink log"); } } catch (SinkError e) { report.addFailedRecord(record.toString(), "Problem during mapping: " + e.getMessage()); } }); sinkTimer.stop(); } else { log.info("TESTRUN, created documents are:\n{}", Arrays.toString(mappedRecords.toArray())); } } catch (RuntimeException e) { if (sourceTimer.isRunning()) { sourceTimer.stop(); } if (mappingTimer.isRunning()) { mappingTimer.stop(); } if (sinkTimer.isRunning()) { sinkTimer.stop(); } String msg = String.format("Problem processing records %s to %s: %s", pageStart, pageStart + size, e.getMessage()); log.error(msg, e); report.addMessage(msg); } pageStart += bulkSize; currentBulkTimer.stop(); bulkTimeAvg = ((bulkTimeAvg * runNumber) + currentBulkTimer.elapsed(TimeUnit.SECONDS)) / (runNumber + 1); updateAndLog(runNumber, (runNumber + 1) * bulkSize, currentBulkTimer.elapsed(TimeUnit.SECONDS), bulkTimeAvg); currentBulkTimer.reset(); runNumber++; } timer.stop(); log.info("Completed harvesting for {} ({} failed) of {} records in {} minutes", report.getNumberOfRecordsAdded(), report.getNumberOfRecordsFailed(), source.getRecordCount(), timer.elapsed(TimeUnit.MINUTES)); log.info("Time spent (minutes): source={}, mapping={}, sink={}", sourceTimer.elapsed(TimeUnit.MINUTES), mappingTimer.elapsed(TimeUnit.MINUTES), sinkTimer.elapsed(TimeUnit.MINUTES)); return report; }
From source file:com.sourcecode.FileInputFormat.java
/** List input directories. * Subclasses may override to, e.g., select only files matching a regular * expression. /*from w w w . j a va 2 s . c o m*/ * * @param job the job to list input paths for * @return array of FileStatus objects * @throws IOException if zero items. */ protected List<FileStatus> listStatus(JobContext job) throws IOException { Path[] dirs = getInputPaths(job); if (dirs.length == 0) { throw new IOException("No input paths specified in job"); } // get tokens for all the required FileSystems.. TokenCache.obtainTokensForNamenodes(job.getCredentials(), dirs, job.getConfiguration()); // Whether we need to recursive look into the directory structure boolean recursive = getInputDirRecursive(job); // creates a MultiPathFilter with the hiddenFileFilter and the // user provided one (if any). List<PathFilter> filters = new ArrayList<PathFilter>(); filters.add(hiddenFileFilter); PathFilter jobFilter = getInputPathFilter(job); if (jobFilter != null) { filters.add(jobFilter); } PathFilter inputFilter = new MultiPathFilter(filters); List<FileStatus> result = null; int numThreads = job.getConfiguration().getInt(LIST_STATUS_NUM_THREADS, DEFAULT_LIST_STATUS_NUM_THREADS); Stopwatch sw = new Stopwatch().start(); if (numThreads == 1) { result = singleThreadedListStatus(job, dirs, inputFilter, recursive); } else { Iterable<FileStatus> locatedFiles = null; try { LocatedFileStatusFetcher locatedFileStatusFetcher = new LocatedFileStatusFetcher( job.getConfiguration(), dirs, recursive, inputFilter, true); locatedFiles = locatedFileStatusFetcher.getFileStatuses(); } catch (InterruptedException e) { throw new IOException("Interrupted while getting file statuses"); } result = Lists.newArrayList(locatedFiles); } sw.stop(); if (LOG.isDebugEnabled()) { LOG.debug("Time taken to get FileStatuses: " + sw.elapsedMillis()); } LOG.info("Total input paths to process : " + result.size()); return result; }