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);
}
}
评论