Apache HttpClient:衡量响应时间的正确方法

问题描述

我正在尝试使用Apache HttpClient测量服务器响应时间。我已经在下面设置了测试代码。我假设tp3显示(发送到接收)时间。在下面的测试中,tp3 = 198.13ms。根据Google Chrome的显示,服务器响应时间为17毫秒(更快的181.13毫秒)。

我错过了什么吗?

使用Apache HttpClient衡量服务器响应时间的最佳方法是什么?


     public static void main(String[] args) throws Exception {

        long tp0 = System.nanoTime();

        CloseableHttpClient httpclient = HttpClients.createDefault();
        long tp1 = System.nanoTime() - tp0;

        HttpGet httpGet = new HttpGet("http://example.com");
        long tp2 = System.nanoTime() - tp0;

        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        long tp3 = System.nanoTime() - tp0;

        long tp4 = 0;
        long tp5 = 0;
        long tp6 = 0;
        long tp7 = 0;
        StatusLine resp;

        try {
            resp = response1.getStatusLine();
            tp4 = System.nanoTime() - tp0;

            httpentity entity1 = response1.getEntity();
            tp5 = System.nanoTime() - tp0;

            EntityUtils.consume(entity1);
            tp6 = System.nanoTime() - tp0;

        } finally {
            response1.close();
            tp7 = System.nanoTime() - tp0;
        }

        System.out.println("tp1 = " + fmt(tp1)); //tp1 = 611.26ms
        System.out.println("tp2 = " + fmt(tp2-tp1)); //tp2 = 3.16ms
        System.out.println("tp3 = " + fmt(tp3-tp2)); //tp3 = 198.13ms
        System.out.println("tp4 = " + fmt(tp4-tp3)); //tp4 = .01ms
        System.out.println("tp5 = " + fmt(tp5-tp4)); //tp5 = .00ms
        System.out.println("tp6 = " + fmt(tp6-tp5)); //tp6 = .91ms
        System.out.println("tp7 = " + fmt(tp7-tp6)); //tp7 = .01ms

        System.out.println("Response = " + resp);

    }

    private static String fmt(double val){
        val = val / 1e6;
        DecimalFormat formatter = new DecimalFormat("#,###,###.00");
        return formatter.format(val) + "ms";
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)