1

在一种方法中,我创建并异步发送一些 HTTPRequest,并将 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
  }
}

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

4

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)));

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

于 2020-06-02T12:48:00.487 回答