【问题标题】:Using Duration.ofMillis with a nanoseconds value使用具有纳秒值的 Duration.ofMillis
【发布时间】:2022-01-24 05:35:59
【问题描述】:

我找到了一段代码实现千分尺计时器,我需要帮助解码以下代码 sn-p,因为我认为我理解不正确。根据我的理解, stopwatch.stop().elapsed(Nanos) 将返回从秒表启动到停止所用的纳秒。

现在对于 Duration.ofMillis,我阅读了 Java 文档,它说应该在这里传递一个毫秒值。这段代码通过了纳秒,所以在这种情况下,duration.ofMillis 部分会起作用吗?假设秒表在 100 毫秒后停止,我认为 Duration.ofMillis 将获得 100000000 的值。我不知道在那之后会发生什么。

Stopwatch stopwatch = Stopwatch.createStarted();
        meterRegistry.timer(name)
                .record(Duration.ofMillis(stopwatch.stop().elapsed(TimeUnit.NANOSECONDS)));

【问题讨论】:

  • 为什么你认为Duration.ofMillis()会得到100 000 000的值?你为什么不试试呢?提示:还有Duration.ofNanos(long nanos)

标签: java guava micrometer


【解决方案1】:

你在哪里找到这个代码sn-p? 对我来说,这似乎是错误的,不仅因为测量结果错误,还因为 Micrometer has such a mechanismmeasuring elapsed time is harder than one would think

你可以这样做:

Timer.Sample sample = Timer.start();
// do stuff
sample.stop(registry.timer(name));

或者这些:

timer.record(() -> doSomething());
timer.recordCallable(() -> getSomething());

或将检测的 Runnable/Callable 传递给 ExecutorService/CompletionService

Runnable r = timer.wrap(() -> doSomething());
Callable c = timer.wrap(() -> getSomething());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    相关资源
    最近更新 更多