【架构师训练营 - week7 -1】作业

发布于: 14 小时前
【架构师训练营 - week7 -1】作业



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

吞吐量=(1000/响应时间ms)x 并发数





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



public class HttpTest {

public static void main(String[] arg) {

int requestCount = 100;
int parallelCount = 10;
long[] responseTimes = new long[requestCount];

for (int i = 0; i < requestCount; i++) {
responseTimes[i] = parallelTesk(parallelCount, () -> {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.baidu.com");
CloseableHttpResponse response;
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
}
} catch (IOException e) {
e.printStackTrace();
}
});
}

Arrays.sort(responseTimes);

long sum = 0;
for (long time : responseTimes) {
sum += time;
}

System.out.println("所有时间:" + Arrays.toString(responseTimes));
System.out.println("平均响应时间:" + sum / responseTimes.length);
System.out.println("95%响应时间:" + responseTimes[94]);
}

public static long parallelTesk(int threadNum, Runnable task) {
final CountDownLatch startGate = new CountDownLatch(1);
final CountDownLatch endGate = new CountDownLatch(threadNum);

for (int i = 0; i < threadNum; i++) {
Thread t = new Thread(() -> {
try {
startGate.await();
try {
task.run();
} finally {
endGate.countDown();
}
} catch (InterruptedException e) {

}
});

t.start();
}

long start = System.currentTimeMillis();

startGate.countDown();
try {
endGate.await();
} catch (InterruptedException e) {
}

long end = System.currentTimeMillis();

return end - start;
}

}



用户头像

早睡早起

关注

还未添加个人签名 2019.09.05 加入

还未添加个人简介

评论

发布
暂无评论
【架构师训练营 - week7 -1】作业