List of usage examples for com.google.common.base Stopwatch stop
public Stopwatch stop()
From source file:processing.MalletCalculator.java
public static List<Map<Integer, Double>> startLdaCreation(BookmarkReader reader, int sampleSize, boolean sorting, int numTopics, boolean userBased, boolean resBased, boolean topicCreation, boolean smoothing) { timeString = ""; int size = reader.getUserLines().size(); int trainSize = size - sampleSize; Stopwatch timer = new Stopwatch(); timer.start();/*from w w w . java 2 s .co m*/ MalletCalculator userCalc = null; List<Map<Integer, Integer>> userMaps = null; //List<Double> userDenoms = null; if (userBased) { userMaps = Utilities.getUserMaps(reader.getUserLines().subList(0, trainSize)); userCalc = new MalletCalculator(userMaps, numTopics); userCalc.predictValuesProbs(); //userDenoms = getDenoms(userPredictionValues); System.out.println("User-Training finished"); } MalletCalculator resCalc = null; List<Map<Integer, Integer>> resMaps = null; //List<Double> resDenoms = null; if (resBased) { resMaps = Utilities.getResMaps(reader.getUserLines().subList(0, trainSize)); resCalc = new MalletCalculator(resMaps, numTopics); resCalc.predictValuesProbs(); //resDenoms = getDenoms(resPredictionValues); System.out.println("Res-Training finished"); } List<Map<Integer, Double>> results = new ArrayList<Map<Integer, Double>>(); if (trainSize == size) { trainSize = 0; } timer.stop(); long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS); timer = new Stopwatch(); timer.start(); for (int i = trainSize; i < size; i++) { // the test set UserData data = reader.getUserLines().get(i); int userID = data.getUserID(); int resID = data.getWikiID(); //Map<Integer, Integer> userMap = null; //if (userBased && userMaps != null && userID < userMaps.size()) { // userMap = userMaps.get(userID); //} //Map<Integer, Integer> resMap = null; //if (resBased && resMaps != null && resID < resMaps.size()) { // resMap = resMaps.get(resID); //} double userTagCount = 0.0;//Utilities.getMapCount(userMap); double resTagCount = 0.0;//Utilities.getMapCount(resMap); /* double userDenomVal = 0.0; if (userDenoms != null && userID < userDenoms.size()) { userDenomVal = userDenoms.get(userID); } double resDenomVal = 0.0; if (resDenoms != null && resID < resDenoms.size()) { resDenomVal = resDenoms.get(resID); } */ Map<Integer, Double> userPredMap = null; if (userCalc != null) { userPredMap = userCalc.getValueProbsForID(userID, topicCreation); } Map<Integer, Double> resPredMap = null; if (resCalc != null) { resPredMap = resCalc.getValueProbsForID(resID, topicCreation); } Map<Integer, Double> map = getRankedTagList(reader, userPredMap, userTagCount, resPredMap, resTagCount, sorting, smoothing, topicCreation); results.add(map); } timer.stop(); long testTime = timer.elapsed(TimeUnit.MILLISECONDS); timeString += ("Full training time: " + trainingTime + "\n"); timeString += ("Full test time: " + testTime + "\n"); timeString += ("Average test time: " + testTime / (double) sampleSize) + "\n"; timeString += ("Total time: " + (trainingTime + testTime) + "\n"); return results; }
From source file:org.graylog2.plugin.indexer.retention.RetentionStrategy.java
public void runStrategy(String indexName) { Stopwatch sw = Stopwatch.createStarted(); if (iterates()) { // TODO: Run per message. }/*from ww w .j ava 2 s . c o m*/ // Delete or close index. switch (getType()) { case DELETE: LOG.info("Strategy is deleting."); indexManagement.delete(indexName); break; case CLOSE: LOG.info("Strategy is closing."); indexManagement.close(indexName); break; } LOG.info("Finished index retention strategy [" + this.getClass().getCanonicalName() + "] for " + "index <{}> in {}ms.", indexName, sw.stop().elapsed(TimeUnit.MILLISECONDS)); }
From source file:nl.knaw.huygens.timbuctoo.rest.resources.DomainEntityResource.java
@APIDesc("Get an number of entities. Query params: \"rows\" (default: 200) and \"start\" (default: 0).") @GET//from ww w .j a va 2s .co m @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_HTML }) public Response getEntities( // @PathParam(ENTITY_PARAM) String entityName, // @QueryParam("type") String typeValue, // @QueryParam("rows") @DefaultValue("200") int rows, // @QueryParam("start") @DefaultValue("0") int start // ) { Stopwatch stopwatch = Stopwatch.createStarted(); LOG.info("Begin retrieving entities: [{}]", entityName); Class<? extends DomainEntity> entityType = getValidEntityType(entityName); List<? extends DomainEntity> list = retrieveEntities(entityType, typeValue, rows, start); LOG.info("Done retrievingEntities: [{}] in [{}]", entityName, stopwatch.stop()); return Response.ok(new GenericEntity<List<? extends DomainEntity>>(list) { }).build(); }
From source file:com.google.devtools.build.lib.pkgcache.LegacyLoadingPhaseRunner.java
private void postLoadingLogging(EventBus eventBus, ImmutableSet<Target> originalTargetsToLoad, ImmutableSet<Target> expandedTargetsToLoad, Stopwatch timer) { Set<Target> testSuiteTargets = Sets.difference(originalTargetsToLoad, expandedTargetsToLoad); eventBus.post(new LoadingPhaseCompleteEvent(expandedTargetsToLoad, testSuiteTargets, packageManager.getStatistics(), timer.stop().elapsed(TimeUnit.MILLISECONDS))); LOG.info("Loading phase finished"); }
From source file:pl.coffeepower.blog.messagebus.MessageBusTestHelper.java
Publisher executePublisher(final Engine engine) throws InterruptedException { Publisher publisher = Guice.createInjector(Stage.PRODUCTION, new TestConfigurationModule(), new BytesEventModule(), engine.getModule()).getInstance(Publisher.class); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(() -> {/*from w w w . j a v a 2 s .c o m*/ Fixtures fixtures = new Fixtures(); Stopwatch stopwatch = Stopwatch.createStarted(); LongStream.rangeClosed(fixtures.getFirstMessageId(), fixtures.getNumberOfMessages()).forEach(value -> { IdleStrategy idleStrategy = new SleepingIdleStrategy(TimeUnit.MICROSECONDS.toNanos(1L)); while (!publisher.send(Bytes.concat(Longs.toByteArray(value), fixtures.getAdditionalData()))) { idleStrategy.idle(); } }); System.out.println("Sent all messages in " + stopwatch.stop()); }); executorService.shutdown(); executorService.awaitTermination(1L, TimeUnit.MINUTES); return publisher; }
From source file:ru.releng.shameonyou.core.Sampler.java
@Override public void run() { if (state.get() == State.STARTED) { Stopwatch responseTimeStopwatch = Stopwatch.createStarted(); boolean preparedSuccessfully = false; recordQueueValue(queueLengthRecorder, inFlight.incrementAndGet()); try {/* w w w .j a v a2s.c o m*/ asyncHttpClient.prepareGet(target.getUrl()).execute(new AsyncCompletionHandler<Void>() { @Override public Void onCompleted(Response response) throws Exception { long responseTime = responseTimeStopwatch.stop().elapsed(TimeUnit.MILLISECONDS); recordTimeValue(responseTimeRecorder, responseTime); recordQueueValue(queueLengthRecorder, inFlight.decrementAndGet()); if (response.getStatusCode() >= 200 && response.getStatusCode() < 300) { successes.incrementAndGet(); } else { totalErrors.incrementAndGet(); errors.incrementAndGet(); } LOG.info("Response {} from {} in {} ms", response.getStatusCode(), target.getUrl(), responseTime); return null; } @Override public void onThrowable(Throwable t) { long responseTime = responseTimeStopwatch.stop().elapsed(TimeUnit.MILLISECONDS); recordTimeValue(responseTimeRecorder, responseTime); recordQueueValue(queueLengthRecorder, inFlight.decrementAndGet()); totalErrors.incrementAndGet(); errors.incrementAndGet(); LOG.info("Failure [{}] from {} in {} ms", t.toString(), target.getUrl(), responseTime); } }); preparedSuccessfully = true; } finally { if (!preparedSuccessfully) { recordQueueValue(queueLengthRecorder, inFlight.decrementAndGet()); totalErrors.incrementAndGet(); errors.incrementAndGet(); } } } }
From source file:com.thinkbiganalytics.nifi.v2.thrift.RefreshableDataSource.java
/** * @param statement statement handle to use for execution * @param validationQuery query to use to check the connection * @param timeout time, in seconds, to wait for the query to complete * @return true if query had to be timed out, false otherwise. *///from w w w . java 2 s .co m private synchronized boolean validateQueryWithTimeout(final Statement statement, final String validationQuery, int timeout) throws SQLException { log.info("perform validation query in RefreshableDatasource.executeWithTimeout()"); final Stopwatch timer = Stopwatch.createStarted(); try { executor.submit(() -> statement.execute(validationQuery)).get(timeout, TimeUnit.SECONDS); log.info("validation query returned from RefreshableDatasource.executeWithTimeout() in {}", timer.stop()); return true; } catch (final InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Unlikely scenario that query thread was interrupted. Application going down?", e); throw new SQLException(e); } catch (final TimeoutException e) { return false; } catch (final Exception e) { Throwables.propagateIfInstanceOf(e.getCause(), SQLException.class); throw Throwables.propagate(e.getCause()); } }
From source file:tds.dll.common.diagnostic.services.impl.DiagnosticDatabaseServiceImpl.java
private DatabaseOperation readOperation(LegacyDbNameUtility.Databases dbName) { Stopwatch stopwatch = Stopwatch.createStarted(); try {//from w ww .j av a2 s. c o m switch (dbName) { case Archive: readTestDao.readArchiveDatabase(); break; case Config: readTestDao.readConfigsDatabase(); break; case Itembank: readTestDao.readItemBankDatabase(); break; case Session: readTestDao.readSessionDatabase(); break; } } catch (DiagnosticException diagnosticException) { stopwatch.stop(); return new DatabaseOperation(Rating.FAILED, DatabaseOperationType.READ, stopwatch.elapsed(TimeUnit.MILLISECONDS), diagnosticException.getMessage()); } return new DatabaseOperation(Rating.IDEAL, DatabaseOperationType.READ, stopwatch.elapsed(TimeUnit.MILLISECONDS)); }
From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java
protected int executeMethod(ProxyRepository repository, ResourceStoreRequest request, HttpMethod method, URL remoteUrl) throws RemoteStorageException { final Stopwatch stopwatch = timingLog.isDebugEnabled() ? new Stopwatch().start() : null; try {/*from w ww. j a v a2s . c o m*/ return doExecuteMethod(repository, request, method, remoteUrl); } finally { if (stopwatch != null) { stopwatch.stop(); timingLog.debug("[{}] {} {} took {}", new Object[] { repository.getId(), method.getName(), remoteUrl, stopwatch }); } } }
From source file:org.apache.brooklyn.rest.filter.LoggingFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String rid = RequestTaggingFilter.getTag(); boolean isInteresting = !UNINTERESTING_METHODS.contains(httpRequest.getMethod().toUpperCase()); boolean shouldLog = (isInteresting && LOG.isDebugEnabled()) || LOG.isTraceEnabled(); boolean requestErrored = false; if (shouldLog) { String message = "Request {} starting: {} {} from {}"; Object[] args = new Object[] { rid, httpRequest.getMethod(), httpRequest.getRequestURI(), httpRequest.getRemoteAddr() }; if (isInteresting) { LOG.debug(message, args);// w w w . j ava2 s . c o m } else { LOG.trace(message, args); } } Stopwatch timer = Stopwatch.createStarted(); try { chain.doFilter(request, response); } catch (Throwable e) { requestErrored = true; isInteresting = true; LOG.warn("Request " + rid + " (" + httpRequest.getMethod() + " " + httpRequest.getRequestURI() + " from " + httpRequest.getRemoteAddr() + ") failed: " + e, e); // Propagate for handling by other filter throw Exceptions.propagate(e); } finally { timer.stop(); // This logging must not happen before chain.doFilter, or FormMapProvider will not work as expected. // Getting the parameter map consumes the request body and only resource methods using @FormParam // will work as expected. isInteresting |= (timer.elapsed(TimeUnit.SECONDS) - REQUEST_DURATION_LOG_POINT.toSeconds()) > 0; if (shouldLog) { boolean includeHeaders = requestErrored || httpResponse.getStatus() / 100 == 5 || LOG.isTraceEnabled(); String message = getRequestCompletedMessage(includeHeaders, Duration.of(timer), rid, httpRequest, httpResponse); if (requestErrored || isInteresting) { LOG.debug(message); } else { LOG.trace(message); } } } }