【问题标题】:How to figure out CPU and IO time in Unix environmentUnix环境下如何计算CPU和IO时间
【发布时间】:2025-12-01 11:30:01
【问题描述】:

我有一个简单的 Multithreaded program 正在调用 External API 并从该 API 获取响应。我正在使用RestTemplate

问题陈述:-

我想知道

What is the estimated CPU and IO time for these calls?

我在 Ubuntu 中工作。

下面是我的程序-

public class RestLnPTest {

    private final static Logger LOG = Logger.getLogger(NokiaLnPTest.class.getName());
    private static int noOfThreads = 10;

    public static void main(String[] args) {

        ExecutorService service = Executors.newFixedThreadPool(noOfThreads);

        try {

            for (int i = 0; i < 100 * noOfThreads; i++) {
                service.submit(new ThreadTask());
            }

            service.shutdown();
            service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

        } catch (InterruptedException e) {

        } catch (Exception e) {

        } finally {
            logHistogramInfo();
        }
    }

    private static void logHistogramInfo() {

     System.out.println(ThreadTask.lookupHistogram);

    }
}

class ThreadTask implements Runnable {

    public static ConcurrentHashMap<Long, AtomicLong> lookupHistogram = new ConcurrentHashMap<Long, AtomicLong>();
    private static final String URL = "SOME_URL";

    @Override
    public void run() {

        RestTemplate restTemplate = new RestTemplate();

        long start = System.nanoTime();

        String result = restTemplate.getForObject(URL, String.class);

        long end = System.nanoTime() - start;

        final AtomicLong before = lookupHistogram.putIfAbsent(end / 1000000, new AtomicLong(1L));

        if (before != null) {
            before.incrementAndGet();
        }
    }
}

我在 Ubuntu 的命令行中运行上述程序-

java - jar REST.jar

谁能一步一步告诉我如何在 Unix 环境中为这些调用找出 CPUIO time ?我只需要粗略估计这些调用。

【问题讨论】:

标签: java rest unix io cpu-time


【解决方案1】:

如果“外部调用”是外部应用程序的执行(例如通过exec()),您可以(理论上)通过将应用程序包装在time 中或使用ac 进程记帐内容来获取一些统计信息。

但是,您似乎想找出服务用于处理单个请求的资源。除了让服务本身进行衡量和报告之外,没有其他方法可以获取这些信息。

您可以从外部(即从客户端)捕获的唯一内容是每个请求的经过时间。

【讨论】:

  • 谢谢斯蒂芬。一点背景——我正在提交容量请求,以确保我们的盒子可以在我们托管服务时处理流量。所以容量人问我 - Any idea what is the estimated CPU and IO time for these calls? 所以我想,我可以在 Unix 环境中计算出这些数字吗?所以这就是我编写一个示例程序来获取这些数字的原因,每当我们的服务准备好时,我也会做同样的事情来计算 CPU 和 IO 时间。
  • 是的,您需要在服务器端进行测量。客户端无法以该粒度获得该信息。
  • 感谢斯蒂芬的建议。你能告诉我该怎么做吗?那是我不确定的部分。任何帮助将不胜感激。
  • 使用 ThreadMXBean API - docs.oracle.com/javase/7/docs/api/java/lang/management/… - 它为您提供 JVM 中可用的所有相关信息。