架构训练营第七周作业
发布于: 2020 年 07 月 21 日
用你熟悉的编程语言写一个 web 性能压测工具,输入参数:URL,请求总次数,并发数。输出参数:平均响应时间,95% 响应时间。用这个测试工具以 10 并发、100 次请求压测 www.baidu.com。
public static void main(String args[]) throws Exception { int concurrencyLevel = 10; int totalCount = 100;
ExecutorService threadPool = Executors.newFixedThreadPool(concurrencyLevel); Future<Long>[] futures = new Future[totalCount]; Long[] costs = new Long[totalCount]; for (int i = 0; i < totalCount; i++) { Future<Long> future = threadPool.submit(new Callable<Long>() { @Override public Long call() throws Exception { try { long start = new Date().getTime(); URL url = new URL("https://www.baidu.com"); URLConnection connection = url.openConnection(); Object content = connection.getContent(); long end = new Date().getTime(); return end - start; } catch (Exception e) { e.printStackTrace(); } return 0l; } }); futures[i] = future; }
for (int i = 0; i < totalCount; i++) { costs[i] = futures[i].get(); } System.out.println("avg cost is: " + getAvgTime(costs) + "ms");
Collections.sort(Arrays.asList(costs)); System.out.println("95 cost is: " + costs[94] + "ms"); }
private static double getAvgTime(Long[] costs) { long total = 0; for (int i = 0; i < costs.length; i++) { total += costs[i]; } return total / costs.length; }复制代码
用一个固定大小的线程池(本例申请 10 个),然后总共 100 个请求往线程池里面扔,10 个线程很快被打满,其他请求排队,模拟 10 个并发的情况。
执行结果如下:
划线
评论
复制
发布于: 2020 年 07 月 21 日阅读数: 51
张锐
关注
还未添加个人签名 2018.08.07 加入
还未添加个人简介











评论 (1 条评论)