有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

异步如何使用Java 11标准HTTPClient测量异步发送的HTTPRequest的运行时间?

在一种方法中,我创建并发送一些HTTPRequests async,并将CF添加到列表中:

// HTTPClient is Java11 standard, package java.net.http;
CompletableFuture<HttpResponse<String>> httpResponseCF = this.httpClient.sendAsync(httpRequest, BodyHandlers.ofString());
list.add(httpResponseCF);

稍后,在另一种方法中,我每隔1秒定期检查我的一些异步发送的HttpRequest是否已经收到:

for(CompletableFuture<HttpResponse<String>> httpResponseCF : list){
  if (httpResponseCF.isDone()) {
    //print out: The time between sending HTTPRequest and receiving HTTPResponse is 25ms
  }
}

问题是,如何测量准确的已用请求时间


共 (1) 个答案

  1. # 1 楼答案

    类似于以下内容的内容应该可以做到这一点:

    long start = System.nanoTime();
    CompletableFuture<HttpResponse<String>> httpResponseCF = 
        this.httpClient.sendAsync(httpRequest, BodyHandlers.ofString()).
        whenComplete((r,t) -> System.out.println("elapsed ns: "
                               + (System.nanoTime() - start)));
    

    免责声明:我还没有实际编译上述内容。。。 这也不是确切的时间,而是你能得到的最佳近似值。与所有事情一样,准确的时间是无法测量的