简体   繁体   English

如何计算Java服务所花费的总时间?

[英]How to calculate total time taken by a service in java?

I'm running a simple java program using multithreading. 我正在使用多线程运行一个简单的Java程序。 Each thread calls a service. 每个线程都调用一个服务。 I want to print the total time taken for a service call. 我想打印维修电话花费的总时间。 Please advise how to do this in multithreading environment. 请告知如何在多线程环境中执行此操作。 My code as shown below is not giving the proper result. 如下所示,我的代码未给出正确的结果。 Please help. 请帮忙。

public class ServiceCaller {
    private long totalTime;

    public void makeRequest() {
        long startTime = System.currentTimeMillis();
        serviceCall()
        long endTime = System.currentTimeMillis();
        totalTime = totalTime+(endTime-startTime);
        System.out.println(DurationFormatUtils.formatDurationHMS(totalTime))
    }
}

Access to totalTime should be synchronized and volatile . totalTime访问应同步易变 Without syncronisation different threads will be writing over the value. 如果没有同步,则不同的线程将覆盖该值。 Without volatile different threads could see different values. 没有volatile,不同的线程可能会看到不同的值。 You can simplify the access by using the wrapper classes such as AtomicLong . 您可以使用AtomicLong等包装器类简化访问。

Depending on the platform you are using you may be able to avoid polluting your service class with unrelated timing code with AOP. 根据所使用的平台,您可能可以避免AOP使用无关的时序代码污染服务类。 Most DI frameworks (include Guice and Spring ) support this. 大多数DI框架(包括GuiceSpring )都支持这一点。

Access to totalTime should be thread safe. 访问totalTime应该是线程安全的。 You can use an AtomicLong 您可以使用AtomicLong

final AtomicLong timeTaken = new AtomicLong(0);

// later
timeTaken.addAndGet(endTime - startTime);

You might like to use System.nanoTime() instead of System.currentTimeMillis() for greater resolution. 您可能希望使用System.nanoTime()而不是System.currentTimeMillis()来获得更高的分辨率。

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

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