写点什么

Week7 作业

用户头像
Shawn
关注
发布于: 2020 年 07 月 18 日



  • 用你熟悉的编程语言写一个 web 性能压测工具,输入参数:URL,请求总次数,并发数。输出参数:平均响应时间,95% 响应时间。用这个测试工具以 10 并发、100 次请求压测 www.baidu.com。



public class PerformanceTest {
private static OkHttpClient client = new OkHttpClient();
public static void main(String[] args) throws InterruptedException {
// String url = "https://www.baidu.com"; // avg 3.6, 95% 32
// String url = "https://u.geekbang.org/"; // avg 5.99 95% 56
// String url = "https://www.google.com/"; // avg 29.42 95% 255
String url = "https://www.taobao.com/"; // avg 43 95% 556
int concurrent = 10;
int count = 100;
CountDownLatch countDownLatch = new CountDownLatch(concurrent);
CopyOnWriteArrayList<Long> result = new CopyOnWriteArrayList<>();
for (int i = 0; i < concurrent; i++) {
new Thread(() -> {
List<Long> statistics = new ArrayList<>();
Supplier<Boolean> test = () -> testUrl(url);
for (int j = 0; j < count; j++) {
statistics.add(recordTest(test));
}
result.addAll(statistics);
countDownLatch.countDown();
}).start();
}
countDownLatch.await();
long sum = 0;
long time95 = -1;
int time95index = (int) (result.size() * 0.95);
for (int i = 0; i < result.size(); i++) {
sum += result.get(i);
if (i == time95index) {
time95 = result.get(i);
}
}
System.out.println("avg: " + (0.1 * sum / result.size()));
System.out.println("95%: " + time95);
}
private static Long recordTest(Supplier<Boolean> test) {
long start = System.currentTimeMillis();
Boolean isSuccess = test.get();
long end = System.currentTimeMillis();
return end - start;
}
private static boolean testUrl(String url) {
Request request = new Request.Builder().get().url(url).build();
try (Response response = client.newCall(request).execute()) {
// System.out.println(response);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}



用户头像

Shawn

关注

还未添加个人签名 2017.10.23 加入

还未添加个人简介

评论

发布
暂无评论
Week7 作业