20

I'm using a Java socket, connected to a server. If I send a HEADER http request, how can I measure the response time from the server? Must I use a provided java timer, or is there an easier way?

I'm looking for a short answer, I don't want to use other protocols etc. Obviously do I neither want to have a solution that ties my application to a specific OS. Please people, IN-CODE solutions only.

4

7 に答える 7

20

curl -s -w "%{time_total}\n" -o /dev/null http://server:3000

于 2012-09-21T08:08:10.983 に答える
14

測定しようとしている正確な間隔、送信する要求の最後のバイトから受信する応答の最初のバイトまでの時間に依存すると思いますか? それとも、応答全体が受信されるまでですか? または、サーバー側の時間のみを測定しようとしていますか?

サーバー側の処理時間のみを測定しようとしている場合、リクエストが到着してレスポンスが返されるまでのネットワーク転送に費やされた時間を計算するのは困難です。それ以外の場合は、ソケットを介して自分でリクエストを管理しているため、システム タイマーをチェックして差を計算することで、任意の 2 つの瞬間の間の経過時間を測定できます。例えば:

public void sendHttpRequest(byte[] requestData, Socket connection) {
    long startTime = System.nanoTime();
    writeYourRequestData(connection.getOutputStream(), requestData);
    byte[] responseData = readYourResponseData(connection.getInputStream());
    long elapsedTime = System.nanoTime() - startTime;
    System.out.println("Total elapsed http request/response time in nanoseconds: " + elapsedTime);
}

このコードは、リクエストの書き込みを開始してから応答の受信を終了するまでの時間を測定し、結果を出力します (特定の読み取り/書き込みメソッドが実装されていると仮定します)。

于 2008-09-16T03:44:09.577 に答える
12

コマンドラインで時間とカールと時間を使用できます。curlの-I引数は、ヘッダーのみを要求するように指示します。

time curl -I 'http://server:3000'
于 2008-09-16T03:11:13.557 に答える
9

このような何かがうまくいくかもしれません

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.lang.time.StopWatch;
//import org.apache.commons.lang3.time.StopWatch

public class Main {

    public static void main(String[] args) throws URIException {
        StopWatch watch = new StopWatch();
        HttpClient client = new HttpClient();
        HttpMethod method = new HeadMethod("http://stackoverflow.com/");
        
        try {
            watch.start();
            client.executeMethod(method);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            watch.stop();
        }
        
        System.out.println(String.format("%s %s %d: %s", method.getName(), method.getURI(), method.getStatusCode(), watch.toString()));
        
    }
}
HEAD http://stackoverflow.com/ 200: 0:00:00.404
于 2008-09-16T03:38:21.353 に答える
3

多分私は何かが欠けているかもしれませんが、なぜあなたはただ使わないのですか:

// open your connection
long start = System.currentTimeMillis();
// send request, wait for response (the simple socket calls are all blocking)
long end = System.currentTimeMillis();
System.out.println("Round trip response time = " + (end-start) + " millis");
于 2008-09-16T03:41:14.483 に答える
0

AOP を使用してソケットへの呼び出しをインターセプトし、応答時間を測定します。

于 2008-09-16T04:54:13.200 に答える