第 7 周作业
发布于: 2020 年 12 月 06 日
作业一:性能压测的时候,随着并发压力的增加,系统响应时间和吞吐量是如何变化,为什么?
根据公式【吞吐量 = (1000/响应时间ms) x 并发数】,随着并发压力的增加,在最佳运行区间,系统响应时间从不变到缓慢变长,吞吐量快速上升。过了最佳运行点后,系统响应时间与吞吐量同步上升。过了最大负载点,系统响应时间快速增加,吞吐量停止甚至快速降低。直至系统崩溃点系统崩溃。
在最佳运行区间,系统资源充足,系统处理和响应请求非常快速,用时很少。过了最佳运行点,系统资源开始紧张,一直到全部被占用,系统资源开始出现排队现象,响应时间开始明显变长。而过了最大负载点,系统资源频繁持续的排除,直至系统崩溃。
作业二:用你熟悉的编程语言写一个Web性能压测工具
输入参数:URL,请求总次数,并发数。输出参数:平均响应时间,95%响应时间。用这个测试工具以10并发,100次请求压测www.baidu.com。
定义输出参数
public class WebTestResult { private int avgResponseTime; private int tp95ResponseTime; public WebTestResult(int avgResponseTime, int tp95ResponseTime) { super(); this.avgResponseTime = avgResponseTime; this.tp95ResponseTime = tp95ResponseTime; } public int getAvgResponseTime() { return avgResponseTime; } public int getTp95ResponseTime() { return tp95ResponseTime; }}
定义HTTP请求的工具方法
public class HttpUtils { public static String doGet(String url) throws ParseException, IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); CloseableHttpResponse response = httpClient.execute(httpget); // String content = EntityUtils.toString(response.getEntity(), "UTF-8"); return ""; }}
测试类,测试并生成结果
public class WebTester { public WebTestResult test(String url, int requestTimes, int concurrentNum) { List<Integer> responses = new Vector<>(); Thread[] threads = new Thread[concurrentNum]; CountDownLatch latch = new CountDownLatch(threads.length); for (int i = 0; i < threads.length; i++) { threads[i] = new Thread(new Runnable() { @Override public void run() { for (int j = 0; j < requestTimes; j++) { try { Long beginTime = System.currentTimeMillis(); HttpUtils.doGet(url); long endTime = System.currentTimeMillis(); responses.add((int) (endTime - beginTime)); } catch (Exception e) { System.out.println("got error " + e.getMessage() + ", finished " + j + " requests"); break; } } latch.countDown(); } }); } for (Thread t : threads) { t.start(); } try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } int avgResponseTime = (int) responses.stream().mapToInt(res -> res.intValue()).average().getAsDouble(); Collections.sort(responses); int tp95Position = requestTimes * concurrentNum * 95 / 100; int tp95ResponseTime = responses.get(tp95Position - 1); return new WebTestResult(avgResponseTime, tp95ResponseTime); }}
public class Main { public static void main(String[] args) { String url = "http://www.baidu.com"; int requestTimes = 1, concurrentNum = 100; WebTester webTester = new WebTester(); WebTestResult result = webTester.test(url, requestTimes, concurrentNum); System.out.printf("test for %s,requestTimes:%d,concurrentNum:%d,avgResponseTime:%d,tp95ResponseTime:%d", url, requestTimes, concurrentNum, result.getAvgResponseTime(), result.getTp95ResponseTime()); try { System.in.read(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
划线
评论
复制
发布于: 2020 年 12 月 06 日阅读数: 17
Steven
关注
还未添加个人签名 2008.07.18 加入
还未添加个人简介
评论