繁体   English   中英

如何在 Java / Springboot 中减少 StopWatch 或 System.currentTimeMillis 的调用

[英]How to reduce calls of StopWatch or System.currentTimeMillis in Java / Springboot

我正在使用秒表(在内部使用System.currentTimeMillis())来计算每 API 的执行和完成时间。 我看到有很多与System.currentTimeMillis()相关的问题。 是否有任何替代或更好的方法来计算每个 API 的时间并替代System.currentTimeMillis() 与在 Linux 中使用System.currentTimeMillis()相比, System.nanotime()速度较慢,因此它不起作用。

秒表代码:-

public stopwatch{
private final long start;
    public Stopwatch() {
        start = System.currentTimeMillis();
    }

    public double elapsedTime() {
        long now = System.currentTimeMillis();
        return (now - start) / 1000.0;
    }}

API 代码:

@GetMapping("/endpoint")
public String endPoint(){
  StopWatch  stopWatch = new StopWatch  ();
  //Some code
  long timeTakenForTApi = stopWatch.elapsedTime();
}

你没有告诉我们任何具体要求,所以我只能做出有根据的猜测。

我想,您想收集 API 调用的性能指标并将它们提供给某种指标数据分析工具,例如 Prometheus、Dynatrace 或 AWS Cloudwatch?

如果真是这样,我就不会开始重新发明轮子了。 你看过https://micrometer.io 了吗?

然后,您将以编程方式使用Timer或在您的 controller 方法上使用@Timed批注,如下所示:

@Timed
@GetMapping("/endpoint")
public String endPoint(){
  //Some code
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM