我的测试表明,以 stackoverflow.com GET 请求为例,重复 10 次以上:
正如您从图像中看到(或未看到),使用 jmeter 和View Results in a Table
. 请注意,此侦听器不会仅打印请求统计信息的响应正文。
这是我的 Java 代码:
public static void main(String[] args) throws Exception{
long totalTimeMS = 0;
for (int i = 0; i < 10; i++) {
long startTime = System.currentTimeMillis();
HttpGet get = new HttpGet("http://stackoverflow.com");
HttpClient client = new DefaultHttpClient();
client.execute(get);
long endTime = System.currentTimeMillis();
long duration = (endTime-startTime);
totalTimeMS +=duration;
System.out.format("Duration %d ms\n", duration);
}
System.out.format("Average time is %d ms", (totalTimeMS/10));
}
所以我也不关心响应体。但这里是结果(快得多):
Duration 615 ms
Duration 263 ms
Duration 264 ms
Duration 262 ms
Duration 268 ms
Duration 266 ms
Duration 265 ms
Duration 266 ms
Duration 268 ms
Duration 263 ms
Average time is 300 ms
现在在 jmeter 中使用另一个案例时View Results in a Tree
,您实际上可以看到响应正文加上 ,View Results in a Table
因为我们仍然需要时间。
我不会附上屏幕截图,因为答案的可读性会降低,但这次的平均时间812 ms
比以前多 100 毫秒。
现在关心响应体的java代码(新方法):
public static String convertStreamToString(InputStream is) throws IOException {
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
我稍微修改了之前的代码,所以它打印出响应,模拟 jmeter 行为,发布相关部分:
HttpGet get = new HttpGet("http://stackoverflow.com");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
long endTime = System.currentTimeMillis();
long duration = (endTime-startTime);
totalTimeMS +=duration;
System.out.println(convertStreamToString(response.getEntity().getContent()));
System.out.format("Duration %d ms\n", duration);
结果如下:
Duration 678 ms + (including printing of response body)
Duration 264 ms + (including printing of response body)
Duration 269 ms + (including printing of response body)
Duration 262 ms + (including printing of response body)
Duration 263 ms + (including printing of response body)
Duration 265 ms + (including printing of response body)
Duration 262 ms + (including printing of response body)
Duration 267 ms + (including printing of response body)
Duration 264 ms + (including printing of response body)
Duration 264 ms + (including printing of response body)
Average time is 305 ms
响应时间增加了5 ms
。所以我不知道 jmeter 是如何比普通的 java 代码更快的。无论如何,jmeter 确实是一个很棒的工具,是最好的工具之一(免费)。