package com.demo.test;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
* @author niki-lauda
* @create 2020-07-19 16:16
*/
public class RequestTimeTest {
private static final int KEEP_ALIVE_TIME = 3;
private CopyOnWriteArrayList<Long> executeTimeList;
private CountDownLatch countDownLatch;
public RequestTimeTest(CopyOnWriteArrayList<Long> executeTimeList, CountDownLatch countDownLatch) {
this.executeTimeList = executeTimeList;
this.countDownLatch = countDownLatch;
}
public void concurrentTest(String url, int totalTimes, int concurrentNum) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(concurrentNum, concurrentNum, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
threadPoolExecutor.allowCoreThreadTimeOut(true);
long start = System.currentTimeMillis();
for (int i = 0; i < totalTimes; i++) {
threadPoolExecutor.execute(() -> {
HttpUtils.doGet(url);
executeTimeList.add(System.currentTimeMillis() - start);
countDownLatch.countDown();
});
}
while(countDownLatch.getCount() != 0) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public double getAverageTime() {
double averageTime = 0;
for (Long executeTime : executeTimeList) {
averageTime += executeTime / executeTimeList.size();
}
return averageTime;
}
public double getResponseTime(int percent) {
return executeTimeList.get(executeTimeList.size() * percent / 100);
}
public static void main(String[] args) {
String url = "https://xie.infoq.cn/";
int totalTimes = 100;
RequestTimeTest timeTest = new RequestTimeTest(new CopyOnWriteArrayList<>(), new CountDownLatch(totalTimes));
timeTest.concurrentTest(url, totalTimes, 10);
System.out.println(String.format("平均响应时间=%.2fms", timeTest.getAverageTime()));
System.out.println(String.format("95%%响应时间=%.2fms", timeTest.getResponseTime(95)));
}
}
评论