• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java Timer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中com.codahale.metrics.Timer的典型用法代码示例。如果您正苦于以下问题:Java Timer类的具体用法?Java Timer怎么用?Java Timer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Timer类属于com.codahale.metrics包,在下文中一共展示了Timer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: TrainingFetcher

import com.codahale.metrics.Timer; //导入依赖的package包/类
TrainingFetcher(MetricSampler metricSampler,
                Cluster cluster,
                SampleStore sampleStore,
                Set<TopicPartition> assignedPartitions,
                long startTimeMs,
                long endTimeMs,
                Timer fetcherTimer,
                Meter fetcherFailureRate) {
  _cluster = cluster;
  _sampleStore = sampleStore;
  _metricSampler = metricSampler;
  _startTimeMs = startTimeMs;
  _endTimeMs = endTimeMs;
  _assignedPartitions = assignedPartitions;
  _fetcherTimer = fetcherTimer;
  _fetcherFailureRate = fetcherFailureRate;
}
 
开发者ID:linkedin,项目名称:cruise-control,代码行数:18,代码来源:TrainingFetcher.java


示例2: fetchMetricsForAssignedPartitions

import com.codahale.metrics.Timer; //导入依赖的package包/类
@Override
protected void fetchMetricsForAssignedPartitions() throws MetricSamplingException {
  final Timer.Context ctx = _fetcherTimer.time();

  try {
    MetricSampler.Samples samples =
        _metricSampler.getSamples(_cluster, _assignedPartitions, _startTimeMs, _endTimeMs, MetricSampler.SamplingMode.BROKER_METRICS_ONLY);
    ModelParameters.addMetricObservation(samples.brokerMetricSamples());

    _sampleStore.storeSamples(samples);
  } catch (Exception e) {
    _fetcherFailureRate.mark();
    throw e;
  } finally {
    ctx.stop();
  }
}
 
开发者ID:linkedin,项目名称:cruise-control,代码行数:18,代码来源:TrainingFetcher.java


示例3: ChangeLoader

import com.codahale.metrics.Timer; //导入依赖的package包/类
/**
 * Create a new {@code ChangeLoader}.
 *
 * @param cxt the Bireme Context
 * @param pipeLine the {@code PipeLine} belongs to
 * @param mappedTable the target table
 * @param taskIn a queue to get {@code LoadTask}
 */
public ChangeLoader(Context cxt, PipeLine pipeLine, String mappedTable,
    LinkedBlockingQueue<Future<LoadTask>> taskIn) {
  this.cxt = cxt;
  this.conf = cxt.conf;
  this.conn = null;
  this.mappedTable = mappedTable;
  this.table = cxt.tablesInfo.get(mappedTable);
  this.taskIn = taskIn;
  this.copyThread = Executors.newFixedThreadPool(1);

  // add statistics
  Timer[] timers = pipeLine.stat.addTimerForLoader(mappedTable);
  copyForDeleteTimer = timers[0];
  deleteTimer = timers[1];
  copyForInsertTimer = timers[2];

  logger = pipeLine.logger;
}
 
开发者ID:HashDataInc,项目名称:bireme,代码行数:27,代码来源:ChangeLoader.java


示例4: sendHealthCheckRequest

import com.codahale.metrics.Timer; //导入依赖的package包/类
public MatchingServiceHealthCheckResponseDto sendHealthCheckRequest(
        final Element matchingServiceHealthCheckRequest,
        final URI matchingServiceUri) {

    // Use a custom timer so that we get separate metrics for each matching service
    final String scope = matchingServiceUri.toString().replace(':','_').replace('/', '_');
    final Timer timer = metricsRegistry.timer(MetricRegistry.name(MatchingServiceHealthCheckClient.class, "sendHealthCheckRequest", scope));
    final Timer.Context context = timer.time();
    HealthCheckResponse healthCheckResponse;
    try {
        healthCheckResponse = client.makeSoapRequestForHealthCheck(matchingServiceHealthCheckRequest, matchingServiceUri);
    } catch(ApplicationException ex) {
        final String errorMessage = MessageFormat.format("Failed to complete matching service health check to {0}.", matchingServiceUri);
        LOG.warn(errorMessage, ex);
        return new MatchingServiceHealthCheckResponseDto(Optional.<String>absent(), Optional.<String>absent());
    } finally {
        context.stop();
    }

    return new MatchingServiceHealthCheckResponseDto(
                Optional.of(XmlUtils.writeToString(healthCheckResponse.getResponseElement())),
                healthCheckResponse.getVersionNumber());
}
 
开发者ID:alphagov,项目名称:verify-hub,代码行数:24,代码来源:MatchingServiceHealthCheckClient.java


示例5: main

import com.codahale.metrics.Timer; //导入依赖的package包/类
public static void main(String[] args) throws InterruptedException {
    Bench<JedisPool> bench = new JedisBench() {
        @Override
        public void executeOperation(String data, JedisPool benchInstance, int threadNumber, int iteration,
                MetricRegistry metrics) {
            Jedis jedis = benchInstance.getResource();
            
            Timer.Context time = metrics.timer("incr").time();
            jedis.incr("incr_" + threadNumber + "_" + iteration);
            time.stop();
            
            jedis.close();
        }
    };
    
    Benchmark benchmark = new Benchmark(bench);
    benchmark.run(args);
}
 
开发者ID:redisson,项目名称:redisson-benchmark,代码行数:19,代码来源:AtomicLongIncBenchmark.java


示例6: removeGraphRelation

import com.codahale.metrics.Timer; //导入依赖的package包/类
private void removeGraphRelation(
    Group group,
    String relation,
    String subjectType,
    String subjectKey,
    String objectType,
    String objectKey,
    Timer timer
) {
  final String rel = REL_MARK;
  final String inv = INV_MARK;

  final String relationHashKey = subjectType + "." + subjectKey;
  final String relationRangeKey = rel + relation + "." + objectType + "." + objectKey;
  timed(timer,
      () -> groupStorage.removeRelation(group, relationHashKey, relationRangeKey));

  final String inverseRelationHashKey = objectType + "." + objectKey;
  final String inverseRelationRangeKey = inv + relation + "." + subjectType + "." + subjectKey;
  timed(timer,
      () -> groupStorage.removeRelation(group, inverseRelationHashKey, inverseRelationRangeKey));
}
 
开发者ID:dehora,项目名称:outland,代码行数:23,代码来源:DefaultGroupService.java


示例7: invoke

import com.codahale.metrics.Timer; //导入依赖的package包/类
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {

    EnableMetricTimer annotation = methodInvocation.getThis().getClass().getAnnotation(EnableMetricTimer.class);

    String name = StringUtils.isBlank(annotation.value())
            ? methodInvocation.getThis().getClass().getName() + "." + methodInvocation.getMethod().getName()
            : annotation.value();

    Timer meter = Jboot.me().getMetric().timer(name);
    Timer.Context timerContext = meter.time();
    try {
        return methodInvocation.proceed();
    } finally {
        timerContext.stop();
    }

}
 
开发者ID:yangfuhai,项目名称:jboot,代码行数:19,代码来源:JbootMetricTimerAopInterceptor.java


示例8: main

import com.codahale.metrics.Timer; //导入依赖的package包/类
public static void main(String[] args) throws InterruptedException {
    Bench<JedisPool> bench = new JedisBench() {
        @Override
        public void executeOperation(String data, JedisPool benchInstance, int threadNumber, int iteration,
                MetricRegistry metrics) {
            Jedis jedis = benchInstance.getResource();

            Timer.Context time = metrics.timer("set").time();
            String key = "set_" + threadNumber;
            jedis.sadd(key, data);
            time.stop();

            jedis.close();
        }
    };
    
    Benchmark benchmark = new Benchmark(bench);
    benchmark.run(args);
}
 
开发者ID:redisson,项目名称:redisson-benchmark,代码行数:20,代码来源:SetAddBenchmark.java


示例9: main

import com.codahale.metrics.Timer; //导入依赖的package包/类
public static void main(String[] args) throws InterruptedException {
    Bench<JedisPool> bench = new JedisBench() {
        @Override
        public void executeOperation(String data, JedisPool benchInstance, int threadNumber, int iteration,
                MetricRegistry metrics) {
            Jedis jedis = benchInstance.getResource();

            Timer.Context time = metrics.timer("list").time();
            String key = "list_" + threadNumber;
            jedis.rpush(key, data);
            time.stop();

            jedis.close();
        }
    };
    
    Benchmark benchmark = new Benchmark(bench);
    benchmark.run(args);
}
 
开发者ID:redisson,项目名称:redisson-benchmark,代码行数:20,代码来源:ListAddBenchmark.java


示例10: rxJava

import com.codahale.metrics.Timer; //导入依赖的package包/类
@Test
public void rxJava() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);

    RxJavaClient client = retrofit.create(RxJavaClient.class);
    client.timed()
            .subscribe(response -> {
                try {
                    assertThat(response.code()).isEqualTo(HttpURLConnection.HTTP_OK);
                    assertThat(response.body()).isEqualTo(RESPONSE_OBJECT);
                } finally {
                    latch.countDown();
                }
            }, error -> {
                throw new RuntimeException("Test failed");
            });
    latch.await(1L, TimeUnit.SECONDS);

    Timer timer = metrics.timer(TIMER_NAME);
    assertThat(timer).isNotNull();
    assertThat(timer.getCount()).isEqualTo(1);
    assertThat(timer.getMeanRate()).isGreaterThan(0);
}
 
开发者ID:cvent,项目名称:retrofit-metrics,代码行数:24,代码来源:TimedCallAdapterFactoryTest.java


示例11: adjustRateLimit

import com.codahale.metrics.Timer; //导入依赖的package包/类
private void adjustRateLimit() {
    final long count = acquireCount.incrementAndGet();
    if (count >= pollOnCount) {
        final Timer commitTimer = actorContext.getOperationTimer(ActorContext.COMMIT);
        double newRateLimit = calculateNewRateLimit(commitTimer, commitTimeoutInSeconds);

        if (newRateLimit < 1.0) {
            newRateLimit = getRateLimitFromOtherDataStores();
        }

        if (newRateLimit >= 1.0) {
            txRateLimiter.setRate(newRateLimit);
            pollOnCount = count + (long) newRateLimit / 2;
        }
    }
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:17,代码来源:TransactionRateLimiter.java


示例12: setup

import com.codahale.metrics.Timer; //导入依赖的package包/类
@Before
public void setup() throws RpcCallException {
    handlerDictionary = new MethodHandlerDictionary();
    handlerDictionary.put("a", null);
    ServiceMethodHandlerUnderTest mockHandlerThrowsRpcCallEx = new ServiceMethodHandlerUnderTest();

    handlerDictionary.put("jsonRpcWithException", mockHandlerThrowsRpcCallEx);

    metricRegistry = mock(MetricRegistry.class);
    when(metricRegistry.counter(anyString())).thenReturn(mock(Counter.class));
    when(metricRegistry.timer(anyString())).thenReturn(mock(Timer.class));

    handlerMetrics = mock(RpcHandlerMetrics.class);
    when(handlerMetrics.getMethodTimer(any(), any(), any())).thenReturn(mock(GoTimer.class));

    servlet = new JsonHandler(handlerDictionary, metricRegistry, handlerMetrics, new ServiceProperties(), null);
}
 
开发者ID:Sixt,项目名称:ja-micro,代码行数:18,代码来源:JsonHandlerTest.java


示例13: assertMetrics

import com.codahale.metrics.Timer; //导入依赖的package包/类
private void assertMetrics() {
    Timer timer = metricRegistry.getTimers().values().iterator().next();
    assertEquals("wrong number of invocations in metric.", 1, timer.getCount());

    assertTrue("wrong value of mean in metric.", timer.getMeanRate() > 0);

    assertEquals("wrong number of meter metrics.", 2, metricRegistry.getMeters().values().size());

    Set<Map.Entry<String, Meter>> entries = metricRegistry.getMeters().entrySet();

    entries.forEach(entry -> {
        if (entry.getKey().endsWith("Metered")) {
            assertEquals(String.format("wrong number of invocations in metric %s", entry.getKey()), 1,
                    entry.getValue().getCount());
        }
    });

}
 
开发者ID:mwiede,项目名称:metrics-feign,代码行数:19,代码来源:FeignOutboundMetricsMethodHandlerTest.java


示例14: onCallbackComplete

import com.codahale.metrics.Timer; //导入依赖的package包/类
public void onCallbackComplete(Operation operation) {
  Long startTime = removeObjectProperty(operation, OPERATION_PROPERTY_NAME);
  if (startTime == null) {
    return;//re-entrant
  }

  String op = Operations.getOperationName(operation);

  long t = clock.getTick() - startTime;
  Timer timer = opVsTimer.computeIfAbsent(op, s -> {
    String metricName = ROOT_NAME.withTags("command", op).toString();
    return RegistryService.getMetricRegistry().timer(metricName);
  });
  timer.update(t, TimeUnit.NANOSECONDS);

}
 
开发者ID:ApptuitAI,项目名称:JInsight,代码行数:17,代码来源:SpymemcachedRuleHelper.java


示例15: onResponseReceived

import com.codahale.metrics.Timer; //导入依赖的package包/类
public void onResponseReceived(HttpRequest request, HttpResponse response) {
  Long startTime = removeObjectProperty(request, START_TIME_PROPERTY_NAME);
  if (startTime == null) {
    return;
  }

  long t = Clock.defaultClock().getTick() - startTime;

  String method = request.getRequestLine().getMethod();
  int statusCode = response.getStatusLine().getStatusCode();

  String metricName = ROOT_NAME.withTags(
      "method", method,
      "status", "" + statusCode).toString();
  Timer timer = RegistryService.getMetricRegistry().timer(metricName);
  timer.update(t, TimeUnit.NANOSECONDS);

}
 
开发者ID:ApptuitAI,项目名称:JInsight,代码行数:19,代码来源:HttpAsyncClientRuleHelper.java


示例16: onGetInputStream

import com.codahale.metrics.Timer; //导入依赖的package包/类
public void onGetInputStream(HttpURLConnection urlConnection, int statusCode) {
  Long startTime = removeObjectProperty(urlConnection, START_TIME_PROPERTY_NAME);
  if (startTime == null) {
    return;
  }

  long t = Clock.defaultClock().getTick() - startTime;
  String method = urlConnection.getRequestMethod();
  String status = "" + statusCode;
  Timer timer = timers.computeIfAbsent(status + method, s -> {
    TagEncodedMetricName metricName = ROOT_NAME.withTags(
        "method", method,
        "status", status);
    return getTimer(metricName);
  });

  timer.update(t, TimeUnit.NANOSECONDS);
}
 
开发者ID:ApptuitAI,项目名称:JInsight,代码行数:19,代码来源:UrlConnectionRuleHelper.java


示例17: setUp

import com.codahale.metrics.Timer; //导入依赖的package包/类
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);

    actorContext = new ActorContext(getSystem(), actorFactory.createActor(Props.create(DoNothingActor.class)),
            new MockClusterWrapper(), new MockConfiguration(), DatastoreContext.newBuilder().build(),
            new PrimaryShardInfoFutureCache()) {
        @Override
        public Timer getOperationTimer(final String operationName) {
            return commitTimer;
        }

        @Override
        public double getTxCreationLimit() {
            return 10.0;
        }
    };

    doReturn(commitTimerContext).when(commitTimer).time();
    doReturn(commitSnapshot).when(commitTimer).getSnapshot();
    for (int i = 1; i < 11; i++) {
        // Keep on increasing the amount of time it takes to complete transaction for each tenth of a
        // percentile. Essentially this would be 1ms for the 10th percentile, 2ms for 20th percentile and so on.
        doReturn(TimeUnit.MILLISECONDS.toNanos(i) * 1D).when(commitSnapshot).getValue(i * 0.1);
    }
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:27,代码来源:ThreePhaseCommitCohortProxyTest.java


示例18: stop

import com.codahale.metrics.Timer; //导入依赖的package包/类
public static void stop(OperationId id, Supplier<Timer> timerSupplier) {
  OperationId lastId = lastId();
  if (lastId != id) {
    //TODO better error handling
    LOGGER.error("Operation Context Mismatch. Expected: " + id + " got " + lastId);
    return;
  }

  OperationContext context = CONTEXT_STACK.get().pop();
  if (context == RENTRANT) {
    return;
  }

  Timer timer = timerSupplier.get();
  if (timer != null) {
    long t = clock.getTick() - context.getStartTime();
    timer.update(t, TimeUnit.NANOSECONDS);
  }
}
 
开发者ID:ApptuitAI,项目名称:JInsight,代码行数:20,代码来源:RuleHelper.java


示例19: report

import com.codahale.metrics.Timer; //导入依赖的package包/类
@Override
public void report(final SortedMap<String, Gauge> gauges,
                   final SortedMap<String, Counter> counters,
                   final SortedMap<String, Histogram> histograms,
                   final SortedMap<String, Meter> meters,
                   final SortedMap<String, Timer> timers) {
  final long timestamp = clock.instant().toEpochMilli();

  final ImmutableList<InfluxDbMeasurement> influxDbMeasurements = ImmutableList.<InfluxDbMeasurement>builder()
    .addAll(transformer.fromGauges(gauges, timestamp))
    .addAll(transformer.fromCounters(counters, timestamp))
    .addAll(transformer.fromHistograms(histograms, timestamp))
    .addAll(transformer.fromMeters(meters, timestamp))
    .addAll(transformer.fromTimers(timers, timestamp))
    .build();

  sender.send(influxDbMeasurements);
}
 
开发者ID:kickstarter,项目名称:dropwizard-influxdb-reporter,代码行数:19,代码来源:InfluxDbMeasurementReporter.java


示例20: send

import com.codahale.metrics.Timer; //导入依赖的package包/类
public ServiceResponse send(List<IUserAccount> users, String message, int messageType,
                            String subject, String port, String logMessage, Integer notif,
                            String eventType) throws MessageHandlingException, IOException {
  xLogger.fine("Entered send");

  // Get the address list
  List<String> addresses = getAddresses(users);
  final Timer.Context context = SMS.equals(type) ? smsTimer.time() : emailTimer.time();
  ServiceResponse resp = null;
  try {
    // Send the message and get response
    resp = doSend(addresses, message, messageType, subject, port, domainId);
  } finally {
    context.stop();
  }
  // Store the response
  if (logging) {
    logMessage(domainId, sendingUserId, logMessage != null ? logMessage : message, users, resp,
        notif, eventType);
  }
  xLogger.fine("Exiting send");
  return resp;
}
 
开发者ID:logistimo,项目名称:logistimo-web-service,代码行数:24,代码来源:MessageService.java



注:本文中的com.codahale.metrics.Timer类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java Transaction类代码示例发布时间:2022-05-20
下一篇:
Java Environment类代码示例发布时间:2022-05-20
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap