Java Code Examples for com.codahale.metrics.Timer#time()

The following examples show how to use com.codahale.metrics.Timer#time() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RecordWriterPerformance.java    From heftydb with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    MetricRegistry metrics = new MetricRegistry();
    ConsoleReporter reporter = PerformanceHelper.consoleReporter(metrics);
    Timer timer = metrics.timer("writes");

    TestFileHelper.createTestDirectory();
    KeyValueGenerator keyValueGenerator = new KeyValueGenerator();
    Value value = new Value(keyValueGenerator.testValue(100));

    DBState state = ConfigGenerator.perfState();
    TableWriter tableWriter = new TableWriter(state.config(), state.paths(), state.tables(), state.snapshots(),
            state.caches(), new Metrics(state.config()));

    for (int i = 0; i < RECORD_COUNT; i++) {
        value.data().rewind();
        Timer.Context watch = timer.time();
        tableWriter.write(ByteBuffers.fromString(i + ""), value.data(), false);
        watch.stop();
    }

    reporter.report();
    tableWriter.close();

    TestFileHelper.cleanUpTestFiles();
}
 
Example 2
Source File: CosmosDataAccessor.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to call a Cosmos method and extract any nested DocumentClientException.
 * @param action the action to call.
 * @param timer the {@link Timer} to use to time the action.  May be null.
 * @return the result of the action.
 * @throws DocumentClientException
 */
private ResourceResponse<Document> executeCosmosAction(Callable<? extends ResourceResponse<Document>> action,
    Timer timer) throws DocumentClientException {
  ResourceResponse<Document> resourceResponse;
  Timer.Context operationTimer = null;
  try {
    if (timer != null) {
      operationTimer = timer.time();
    }
    resourceResponse = action.call();
  } catch (RuntimeException rex) {
    if (rex.getCause() instanceof DocumentClientException) {
      throw (DocumentClientException) rex.getCause();
    }
    throw rex;
  } catch (Exception ex) {
    throw new RuntimeException("Exception calling action " + action, ex);
  } finally {
    if (operationTimer != null) {
      operationTimer.stop();
    }
  }
  return resourceResponse;
}
 
Example 3
Source File: RecordBlockPerformance.java    From heftydb with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    MetricRegistry metrics = new MetricRegistry();
    ConsoleReporter reporter = PerformanceHelper.consoleReporter(metrics);
    Timer timer = metrics.timer("reads");
    TupleGenerator generator = new TupleGenerator();
    List<Tuple> tuples = generator.testRecords(1, 64000, 20, 16, 100);

    TupleBlock.Builder blockBuilder = new TupleBlock.Builder();
    for (Tuple tuple : tuples) {
        blockBuilder.addRecord(tuple);
    }

    TupleBlock block = blockBuilder.build();

    Random random = new Random(System.nanoTime());
    int iterations = 10000000;

    for (int i = 0; i < iterations; i++) {
        Timer.Context watch = timer.time();
        block.get(tuples.get(random.nextInt(tuples.size())).key());
        watch.stop();
    }

    reporter.report();
}
 
Example 4
Source File: MonitoringInvocationHandler.java    From Ratel with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(Object o, Method method, Object[] args) throws Throwable {
    Timer timer = fetchTimer(method);

    final Timer.Context context = timer.time();
    final Object returned;
    try {
        returned = method.invoke(object, args);
    } catch (InvocationTargetException e) {
        // Invoked method threw a checked exception.
        // We must rethrow it. The client won't see the interceptor.
        throw e.getTargetException();
    } finally {
        context.stop();
        collectStatistics(method, timer);
    }
    return returned;
}
 
Example 5
Source File: CosmosDataAccessor.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to call Cosmos document query method and record the query time.
 * @param partitionPath the partition to query.
 * @param sqlQuerySpec the DocumentDB query to execute.
 * @param feedOptions {@link FeedOptions} object specifying the options associated with the method.
 * @param timer the {@link Timer} to use to record query time (excluding waiting).
 * @return {@link BlockingObservable} object containing the query response.
 */
private BlockingObservable<FeedResponse<Document>> executeCosmosQuery(String partitionPath, SqlQuerySpec sqlQuerySpec,
    FeedOptions feedOptions, Timer timer) {
  azureMetrics.documentQueryCount.inc();
  logger.debug("Running query on partition {}: {}", partitionPath, sqlQuerySpec.getQueryText());
  Timer.Context operationTimer = timer.time();
  try {
    return asyncDocumentClient.queryDocuments(cosmosCollectionLink, sqlQuerySpec, feedOptions).toBlocking();
  } finally {
    operationTimer.stop();
  }
}
 
Example 6
Source File: MetricsServiceImpl.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
private <T> T time(Timer timer, Callable<T> callable) {
    try {
        // TODO Should this method always return an observable?
        // If so, than we should return Observable.error(e) in the catch block
        return timer.time(callable);
    } catch (Exception e) {
        throw new RuntimeException("There was an error during a timed event", e);
    }
}
 
Example 7
Source File: Metrics.java    From joinery with GNU General Public License v3.0 5 votes vote down vote up
@Around("execution(@com.codahale.metrics.annotation.Timed * *(..))")
public Object injectTimer(final ProceedingJoinPoint point)
throws Throwable {
    final Signature signature = point.getSignature();
    final Annotation annotation = getAnnotation(signature, Timed.class);
    final Timed timed = Timed.class.cast(annotation);
    final String name = name(signature, timed.name(), "timer", timed.absolute());
    final Timer timer = registry.timer(name);
    final Timer.Context context = timer.time();
    try {
        return point.proceed(point.getArgs());
    } finally {
        context.stop();
    }
}
 
Example 8
Source File: PerformanceTest.java    From metrics-sql with Apache License 2.0 5 votes vote down vote up
@Test
public void testPerformance() throws SQLException {
    Timer timer = metricRegistry.timer(MetricRegistry.name(getClass(), name));
    final int iterations = 100, inserts=10; // Increase iterations
    for(int i=0;i<iterations;i++) { final
        Timer.Context context = timer.time();
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("insert into METRICS_TEST(ID, TEXT, CREATED) values (?,?,?)");
        for(int j=0;j<inserts;j++) {
            preparedStatement.setInt(1, i*inserts+j+100);
            preparedStatement.setString(2, "Performance #"+i*10+j);
            preparedStatement.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
            preparedStatement.execute();
        }
        H2DbUtil.close(preparedStatement);
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("select count(*) from METRICS_TEST");
        if (resultSet.next()) {
            int count = resultSet.getInt(1);
        }
        H2DbUtil.close(resultSet);
        resultSet = statement.executeQuery("select * from METRICS_TEST order by ID desc limit 100");
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String text = resultSet.getString("text");
            Timestamp timestamp = resultSet.getTimestamp("created");
        }
        H2DbUtil.close(resultSet, statement, connection);
        context.stop();
    }        
    final Snapshot snapshot = timer.getSnapshot();
    LOGGER.info("End name={} 98%={}, 50%={}", name, snapshot.get98thPercentile(), snapshot.getMean());
}
 
Example 9
Source File: DropWizardMetricsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void collect_Timer() throws InterruptedException {
  Timer timer = metricRegistry.timer("requests");
  Timer.Context context = timer.time();
  Thread.sleep(1L);
  context.stop();

  ArrayList<Metric> metrics = new ArrayList<>(dropWizardMetrics.getMetrics());
  assertThat(metrics.size()).isEqualTo(1);

  assertThat(metrics.get(0).getMetricDescriptor())
      .isEqualTo(
          MetricDescriptor.create(
              "codahale_requests_timer",
              "Collected from codahale (metric=requests, " + "type=com.codahale.metrics.Timer)",
              NS_UNIT,
              Type.SUMMARY,
              Collections.<LabelKey>emptyList()));
  assertThat(metrics.get(0).getTimeSeriesList().size()).isEqualTo(1);
  assertThat(metrics.get(0).getTimeSeriesList().get(0).getLabelValues().size()).isEqualTo(0);
  assertThat(metrics.get(0).getTimeSeriesList().get(0).getPoints().size()).isEqualTo(1);
  assertThat(metrics.get(0).getTimeSeriesList().get(0).getPoints().get(0).getValue())
      .isEqualTo(
          Value.summaryValue(
              Summary.create(
                  1L,
                  0.0,
                  Snapshot.create(
                      1L,
                      0.0,
                      Arrays.asList(
                          ValueAtPercentile.create(50.0, timer.getSnapshot().getMedian()),
                          ValueAtPercentile.create(75.0, timer.getSnapshot().get75thPercentile()),
                          ValueAtPercentile.create(98.0, timer.getSnapshot().get98thPercentile()),
                          ValueAtPercentile.create(99.0, timer.getSnapshot().get99thPercentile()),
                          ValueAtPercentile.create(
                              99.9, timer.getSnapshot().get999thPercentile()))))));
  assertThat(metrics.get(0).getTimeSeriesList().get(0).getStartTimestamp()).isNotNull();
}
 
Example 10
Source File: ReadPerformance.java    From heftydb with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Random random = new Random(System.nanoTime());

    Config config = new Config.Builder().directory(TestFileHelper.TEMP_PATH).compactionStrategy
            (CompactionStrategies.SIZE_TIERED_COMPACTION_STRATEGY).tableCacheSize(512000000).indexCacheSize
            (64000000).maxWriteRate(Integer.MAX_VALUE).build();

    MetricRegistry metrics = new MetricRegistry();
    ConsoleReporter reporter = PerformanceHelper.consoleReporter(metrics);
    Timer readTimer = metrics.register("reads", new Timer(new ExponentiallyDecayingReservoir()));

    DB db = HeftyDB.open(config);

    db.compact().get();

    //Read
    for (int i = 0; i < RECORD_COUNT * 10; i++) {
        String key = random.nextInt(RECORD_COUNT) + "";
        Timer.Context watch = readTimer.time();
        db.get(ByteBuffers.fromString(key));
        watch.stop();
    }

    reporter.report();
    db.logMetrics();
    db.close();

    System.exit(0);
}
 
Example 11
Source File: ScanPerformance.java    From heftydb with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    MetricRegistry metrics = new MetricRegistry();
    ConsoleReporter reporter = PerformanceHelper.consoleReporter(metrics);
    Timer scanTimer = metrics.timer("scans");

    TestFileHelper.createTestDirectory();
    KeyValueGenerator keyValueGenerator = new KeyValueGenerator();
    Value value = new Value(keyValueGenerator.testValue(100));

    Config config = ConfigGenerator.defaultConfig();

    //Write
    final DB db = HeftyDB.open(config);

    for (int i = 0; i < RECORD_COUNT; i++) {
        value.data().rewind();
        db.put(ByteBuffers.fromString(i + ""), value.data());
    }

    //Scan
    Iterator<Record> iterator = db.ascendingIterator(Snapshot.MAX);

    while (iterator.hasNext()) {
        Timer.Context watch = scanTimer.time();
        iterator.next();
        watch.stop();
    }

    db.close();

    reporter.report();

    TestFileHelper.cleanUpTestFiles();
}
 
Example 12
Source File: MetricTypesExample.java    From semantic-metrics with Apache License 2.0 5 votes vote down vote up
/**
 * A timer measures both the rate that a particular piece of code is called and the distribution
 * of its duration. For example we want to measure the rate and handling duration of incoming
 * requests.
 */
private static void reportTimer() {
    // Create or fetch (if it is already created) the metric.
    final Timer timer = registry.timer(
        APP_PREFIX.tagged("what", "incoming-request-time").tagged("endpoint", "/v1/get_stuff"));

    // Do this before starting to do the thing. This creates a measurement context object
    // that you can pass around.
    final Context context = timer.time();

    // Do stuff that takes time (e.g., process the request)
    try {
        Thread.sleep(100);
    } catch (final InterruptedException e) {
        e.printStackTrace();
    }

    // Tell the context that it's done. This will register the duration and counts one
    // occurrence.
    context.stop();

    // That's it! The rest will be automatically done inside semantic metrics library. The
    // reported measurements will be kept in the registry.
    // Every time the reporter wants to report, different stats and aggregations (all the
    // stats that you would get from a meter and a histogram are included) will be calculated
    // and
    // datapoints will be created and reported.
}
 
Example 13
Source File: BlockCreationPerformance.java    From heftydb with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    MetricRegistry metrics = new MetricRegistry();
    ConsoleReporter reporter = PerformanceHelper.consoleReporter(metrics);
    Timer timer = metrics.timer("blockCreationTime");

    KeyValueGenerator generator = new KeyValueGenerator();
    List<Key> keys = new ArrayList<Key>();

    for (int i = 0; i < 64000; i++) {
        keys.add(new Key(generator.testKey(32, 0), i));
    }

    Collections.sort(keys);

    IndexBlock.Builder blockBuilder = new IndexBlock.Builder();

    for (Key key : keys) {
        blockBuilder.addRecord(new IndexRecord(key, 0, 128));
    }

    IndexBlock block = blockBuilder.build();
    MemoryPointer blockPointer = block.memory();

    int iterations = 10000000;

    for (int i = 0; i < iterations; i++) {
        Timer.Context watch = timer.time();
        block = new IndexBlock(new SortedByteMap(blockPointer));
        watch.stop();
    }

    reporter.report();
}
 
Example 14
Source File: CompiledRoutes.java    From xrpc with Apache License 2.0 5 votes vote down vote up
/**
 * Returns compiled routes built from the given route map.
 *
 * @param metricRegistry the registry to generate per-(route,method) rate statistics in
 */
public CompiledRoutes(
    Map<RoutePath, Map<HttpMethod, Handler>> rawRoutes, MetricRegistry metricRegistry) {
  // Build a sorted map of the routes.
  ImmutableSortedMap.Builder<RoutePath, ImmutableMap<HttpMethod, Handler>> routesBuilder =
      ImmutableSortedMap.naturalOrder();
  for (Map.Entry<RoutePath, Map<HttpMethod, Handler>> routeEntry : rawRoutes.entrySet()) {
    ImmutableMap.Builder<HttpMethod, Handler> handlers = new ImmutableMap.Builder<>();
    RoutePath route = routeEntry.getKey();
    for (Map.Entry<HttpMethod, Handler> methodHandlerEntry : routeEntry.getValue().entrySet()) {
      HttpMethod method = methodHandlerEntry.getKey();

      // Wrap the user-provided handler in one that tracks request rates.
      String metricName = MetricRegistry.name("routes", method.name(), route.toString());
      String timerName = MetricRegistry.name("routeLatency", method.name(), route.toString());
      final Handler userHandler = methodHandlerEntry.getValue();
      final Meter meter = metricRegistry.meter(metricName);
      final Timer timer = metricRegistry.timer(timerName);

      // TODO (AD): Pull this out into an adapted handler in a separate class.
      Handler adaptedHandler =
          request -> {
            meter.mark();
            try {
              return timer.time(() -> userHandler.handle(request));
            } catch (Exception e) {
              return request.connectionContext().exceptionHandler().handle(request, e);
            }
          };
      handlers.put(method, adaptedHandler);
    }

    routesBuilder.put(route, handlers.build());
  }

  this.routes = routesBuilder.build();
}
 
Example 15
Source File: IndexBlockPerformance.java    From heftydb with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    MetricRegistry metrics = new MetricRegistry();
    ConsoleReporter reporter = PerformanceHelper.consoleReporter(metrics);
    Timer timer = metrics.timer("reads");

    KeyValueGenerator generator = new KeyValueGenerator();
    List<Key> keys = new ArrayList<Key>();

    for (int i = 0; i < 64000; i++) {
        keys.add(new Key(generator.testKey(32, 0), i));
    }

    Collections.sort(keys);

    IndexBlock.Builder blockBuilder = new IndexBlock.Builder();
    for (Key key : keys) {
        blockBuilder.addRecord(new IndexRecord(key, 0, 128));
    }

    IndexBlock block = blockBuilder.build();

    Random random = new Random(System.nanoTime());
    int iterations = 10000000;

    for (int i = 0; i < iterations; i++) {
        Timer.Context watch = timer.time();
        block.get(keys.get(random.nextInt(keys.size())));
        watch.stop();
    }

    reporter.report();
}
 
Example 16
Source File: Metrics.java    From para with Apache License 2.0 4 votes vote down vote up
private Context(Timer systemTimer, Timer appTimer) {
	this.systemContext = systemTimer.time();
	this.appContext = appTimer == null ? null : appTimer.time();
}
 
Example 17
Source File: SegmentedRaftLog.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
void startTimerOnEnqueue(Timer queueTimer) {
  queueTimerContext = queueTimer.time();
}
 
Example 18
Source File: MediaScannerServiceTestCase.java    From airsonic with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Tests the MediaScannerService by scanning the test media library into an empty database.
 */
@Test
public void testScanLibrary() {
    musicFolderDao.getAllMusicFolders().forEach(musicFolder -> musicFolderDao.deleteMusicFolder(musicFolder.getId()));
    MusicFolderTestData.getTestMusicFolders().forEach(musicFolderDao::createMusicFolder);
    settingsService.clearMusicFolderCache();

    Timer globalTimer = metrics.timer(MetricRegistry.name(MediaScannerServiceTestCase.class, "Timer.global"));

    Timer.Context globalTimerContext = globalTimer.time();
    TestCaseUtils.execScan(mediaScannerService);
    globalTimerContext.stop();

    System.out.println("--- Report of records count per table ---");
    Map<String, Integer> records = TestCaseUtils.recordsInAllTables(daoHelper);
    records.keySet().forEach(tableName -> System.out.println(tableName + " : " + records.get(tableName).toString()));
    System.out.println("--- *********************** ---");


    // Music Folder Music must have 3 children
    List<MediaFile> listeMusicChildren = mediaFileDao.getChildrenOf(new File(MusicFolderTestData.resolveMusicFolderPath()).getPath());
    Assert.assertEquals(3, listeMusicChildren.size());
    // Music Folder Music2 must have 1 children
    List<MediaFile> listeMusic2Children = mediaFileDao.getChildrenOf(new File(MusicFolderTestData.resolveMusic2FolderPath()).getPath());
    Assert.assertEquals(1, listeMusic2Children.size());

    System.out.println("--- List of all artists ---");
    System.out.println("artistName#albumCount");
    List<Artist> allArtists = artistDao.getAlphabetialArtists(0, Integer.MAX_VALUE, musicFolderDao.getAllMusicFolders());
    allArtists.forEach(artist -> System.out.println(artist.getName() + "#" + artist.getAlbumCount()));
    System.out.println("--- *********************** ---");

    System.out.println("--- List of all albums ---");
    System.out.println("name#artist");
    List<Album> allAlbums = albumDao.getAlphabeticalAlbums(0, Integer.MAX_VALUE, true, true, musicFolderDao.getAllMusicFolders());
    allAlbums.forEach(album -> System.out.println(album.getName() + "#" + album.getArtist()));
    Assert.assertEquals(5, allAlbums.size());
    System.out.println("--- *********************** ---");

    List<MediaFile> listeSongs = mediaFileDao.getSongsByGenre("Baroque Instrumental", 0, 0, musicFolderDao.getAllMusicFolders());
    Assert.assertEquals(2, listeSongs.size());

    // display out metrics report
    ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build();
    reporter.report();

    System.out.print("End");
}
 
Example 19
Source File: Instrumentation.java    From blueflood with Apache License 2.0 4 votes vote down vote up
public Timer.Context getTimerContext(String queryCF, boolean batch) {
    final String metricName = (batch ? MetricRegistry.name("batched-", queryCF) : queryCF);

    final Timer timer = Metrics.timer(Instrumentation.class, "reads", metricName);
    return timer.time();
}
 
Example 20
Source File: MetricsUtil.java    From onos with Apache License 2.0 3 votes vote down vote up
/**
 * Starts the Metric Timer.
 * <p>
 * If the given timer was null, it will silently return null.
 * </p>
 *
 * @param timer timer to start
 * @return timing context, if timer was not null
 */
public static Context startTimer(Timer timer) {
    if (timer != null) {
        return timer.time();
    }
    return null;
}