写点什么

架构师训练营第 7 周课后练习

用户头像
叶纪想
关注
发布于: 2020 年 11 月 08 日

题目

  1. 性能压测的时候,随着并发压力的增加,系统响应时间和吞吐量如何变化,为什么?

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

解答



1.第一阶段,系统资源富足,随着并发增加,响应时间平稳,吞吐量线性增加。第二阶段,系统资源吃紧,请求排队等待时间增大,响应时间变长,吞吐量继续增加,但是增加速度变缓。第三阶段,系统资源不足,响应时间明显变长,根据公式 吞吐量 = (1000/响应时间ms)x 并发数,响应时间增长速度比并发数快,吞吐量会变小。

2.测试程序

public class PerformanceTest {
/**
* 测试某个url的平均响应时间,95%响应时间
*
* @param url 测试url
* @param totalRequestNum 总请求数
* @param concurrentNum 并发数
* @throws InterruptedException
*/
public void test(String url, int totalRequestNum, int concurrentNum) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(concurrentNum);
AtomicLong atomicLong = new AtomicLong();
CopyOnWriteArrayList<Long> copyOnWriteArrayList = new CopyOnWriteArrayList<>();
CountDownLatch countDownLatch = new CountDownLatch(totalRequestNum);
for (int i = 0; i < totalRequestNum; i++) {
executorService.submit(() -> {
try {
URL url1 = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();
long st = System.currentTimeMillis();
urlConnection.connect();
long costTime = System.currentTimeMillis() - st;
atomicLong.addAndGet(costTime);
copyOnWriteArrayList.add(costTime);
countDownLatch.countDown();
} catch (IOException e) {
e.printStackTrace();
}
});
}
countDownLatch.await();
System.out.println("平均响应时间:" + atomicLong.get() / totalRequestNum + "ms");
copyOnWriteArrayList.sort(Long::compareTo);
System.out.println("95%响应时间:" + copyOnWriteArrayList.get(Math.round(0.95f * copyOnWriteArrayList.size())) + "ms");
executorService.shutdown();
}
public static void main(String[] args) throws IOException, InterruptedException {
new PerformanceTest().test("http://www.baidu.com", 100, 10);
}
}

执行结果:

平均响应时间:17ms

95%响应时间:26ms

用户头像

叶纪想

关注

还未添加个人签名 2018.05.23 加入

还未添加个人简介

评论

发布
暂无评论
架构师训练营第 7 周课后练习