import cn.hutool.http.HttpUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
public class PerformanceTest {
public static List<Long> resultlist = new ArrayList<Long>();
public static ReentrantLock lock = new ReentrantLock();
/**
* 性能测试
* @param url 测试地址
* @param requestNum 请求总次数
* @param concurrencyNum 并发数
*/
public static void test(String url,int requestNum,int concurrencyNum){
BlockingQueue<Runnable> blockingQueue=new ArrayBlockingQueue<Runnable>(requestNum);
ThreadPoolExecutor pool=new ThreadPoolExecutor(concurrencyNum,concurrencyNum,3, TimeUnit.MILLISECONDS,blockingQueue);
CountDownLatch countDown = new CountDownLatch(requestNum);
for(int i=0;i<requestNum;i++){
pool.execute(()->{
Long start = System.currentTimeMillis();
HttpUtil.get(url);
Long end = System.currentTimeMillis();
lock.lock();
resultlist.add(end-start);
lock.unlock();
countDown.countDown();
});
}
try {
countDown.await();
System.out.println("平均值:"+resultlist.stream().mapToLong(Long::longValue).average().orElse(0)+"ms");
resultlist = resultlist.stream().sorted().collect(Collectors.toList());
int per_95 = (int)( requestNum * 0.95);
System.out.println("95% 响应时间:"+resultlist.get(per_95-1)+"ms");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
test("www.baidu.com",100,10);
}
}
评论