作业 -07- 性能优化

用户头像
梦子说
关注
发布于: 2020 年 07 月 22 日



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

压测的时候,随着并发压力的增加,系统的响应时间越来越大,吞吐量越来越小。因为随着并发越来越大,系统资源将逐渐被耗尽,直至系统崩溃,这就导致系统响应时间越来越大,而吞吐量与下同响应时间呈反向关系,响应时间越大,吞吐量越小。

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



package com.example.demo;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
/**
* 压力测试
*/
public class StressTest {
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, new Runnable() {
@Override
public void run() {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.baidu.com");
CloseableHttpResponse response = null;
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("所有时间:"+ StringUtils.join(responseTimes,','));
System.out.println("平均响应时间:" + sum / responseTimes.length);
System.out.println("95%响应时间:" + responseTimes[94]);
}
/**
* 高并发测试
*
* @param threadNum
* @param task
*/
public static long parallelTesk(int threadNum, Runnable task) {
// 1. 定义闭锁来拦截线程
final CountDownLatch startGate = new CountDownLatch(1);
final CountDownLatch endGate = new CountDownLatch(threadNum);
// 2. 创建指定数量的线程
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();
}
// 3. 线程统一放行,并记录时间!
long start = System.currentTimeMillis();
startGate.countDown();
try {
endGate.await();
} catch (InterruptedException e) {
}
long end = System.currentTimeMillis();
return end - start;
}
}

输出结果:

所有时间响应:[57,57,57,58,58,58,58,58,59,59,59,59,59,59,60,60,60,60,61,61,61,61,61,61,61,61,61,61,62,62,62,62,62,62,62,63,63,63,63,63,63,64,64,64,64,64,64,64,64,65,65,65,65,66,66,66,67,67,67,67,69,69,69,69,69,70,71,73,75,75,77,77,79,84,85,85,86,87,93,96,121,127,129,129,130,141,145,146,154,158,174,204,207,257,289,293,295,303,708,1066]

平均响应时间:104

95%响应时间:289



用户头像

梦子说

关注

还未添加个人签名 2018.12.01 加入

还未添加个人简介

评论

发布
暂无评论
作业-07-性能优化