下面列出了org.springframework.util.StopWatch#stop ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testSingletonLookupByTypeIsFastEnough() {
Assume.group(TestGroup.PERFORMANCE);
Assume.notLogging(factoryLog);
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
lbf.registerBeanDefinition("test", new RootBeanDefinition(TestBean.class));
lbf.freezeConfiguration();
StopWatch sw = new StopWatch();
sw.start("singleton");
for (int i = 0; i < 1000000; i++) {
lbf.getBean(TestBean.class);
}
sw.stop();
// System.out.println(sw.getTotalTimeMillis());
assertTrue("Singleton lookup took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 1000);
}
public void invokeOrderServices(int orderId, int nrOfCalls) {
StopWatch stopWatch = new StopWatch(nrOfCalls + " OrderService call(s)");
Map orderServices = this.beanFactory.getBeansOfType(OrderService.class);
for (Iterator it = orderServices.keySet().iterator(); it.hasNext();) {
String beanName = (String) it.next();
OrderService orderService = (OrderService) orderServices.get(beanName);
System.out.println("Calling OrderService '" + beanName + "' with order ID " + orderId);
stopWatch.start(beanName);
Order order = null;
for (int i = 0; i < nrOfCalls; i++) {
order = orderService.getOrder(orderId);
}
stopWatch.stop();
if (order != null) {
printOrder(order);
}
else {
System.out.println("Order with ID " + orderId + " not found");
}
System.out.println();
}
System.out.println(stopWatch.prettyPrint());
}
/**
* 相同条件下,同样的业务逻辑和IO下,比较抛异常和不抛异常场景下,
* 在性能上有什么区别
*/
@Test
public void givenTwoScenario_whenOneHasExceptionAndAnotherNot_thenGetTheElapsedTime() {
int length = 1000000;
StopWatch stopWatch = new StopWatch("OneHasExceptionAndAnotherNot");
stopWatch.start("hasNoException");
for (int i = 0; i < length; i++) {
doBizHasNoException(String.valueOf(i));
}
stopWatch.stop();
stopWatch.start("hasException");
for (int i = 0; i < length; i++) {
doBizHasException(String.valueOf(i));
}
stopWatch.stop();
log.info("{}", stopWatch.prettyPrint());
}
@Override
public ApplicationMap selectApplicationMapWithScatterData(List<TransactionId> transactionIdList, Range originalRange, Range scanRange, int xGroupUnit, int yGroupUnit, Filter<List<SpanBo>> filter, int version) {
Objects.requireNonNull(transactionIdList, "transactionIdList");
Objects.requireNonNull(originalRange, "originalRange");
Objects.requireNonNull(scanRange, "scanRange");
Objects.requireNonNull(filter, "filter");
StopWatch watch = new StopWatch();
watch.start();
final List<List<SpanBo>> filterList = selectFilteredSpan(transactionIdList, filter);
FilteredMapBuilder filteredMapBuilder = new FilteredMapBuilder(applicationFactory, registry, originalRange, version);
filteredMapBuilder.serverMapDataFilter(serverMapDataFilter);
filteredMapBuilder.addTransactions(filterList);
FilteredMap filteredMap = filteredMapBuilder.build();
ApplicationMap map = createMap(originalRange, filteredMap);
Map<Application, ScatterData> applicationScatterData = filteredMap.getApplicationScatterData(originalRange.getFrom(), originalRange.getTo(), xGroupUnit, yGroupUnit);
ApplicationMapWithScatterData applicationMapWithScatterData = new ApplicationMapWithScatterData(map, applicationScatterData);
watch.stop();
logger.debug("Select filtered application map elapsed. {}ms", watch.getTotalTimeMillis());
return applicationMapWithScatterData;
}
/**
* @Test
* public void testPrototypeCreationIsFastEnough2() throws Exception {
* if (factoryLog.isTraceEnabled() || factoryLog.isDebugEnabled()) {
* // Skip this test: Trace logging blows the time limit.
* return;
* }
* DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
* Method setBeanNameMethod = TestBean.class.getMethod("setBeanName", String.class);
* Method setBeanFactoryMethod = TestBean.class.getMethod("setBeanFactory", BeanFactory.class);
* StopWatch sw = new StopWatch();
* sw.start("prototype");
* for (int i = 0; i < 100000; i++) {
* TestBean tb = TestBean.class.newInstance();
* setBeanNameMethod.invoke(tb, "test");
* setBeanFactoryMethod.invoke(tb, lbf);
* }
* sw.stop();
* // System.out.println(sw.getTotalTimeMillis());
* assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 500);
* }
*/
@Test
@Ignore // TODO re-enable when ConstructorResolver TODO sorted out
public void testPrototypeCreationWithConstructorArgumentsIsFastEnough() {
Assume.group(TestGroup.PERFORMANCE);
Assume.notLogging(factoryLog);
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(TestBean.class);
rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
rbd.getConstructorArgumentValues().addGenericArgumentValue("juergen");
rbd.getConstructorArgumentValues().addGenericArgumentValue("99");
lbf.registerBeanDefinition("test", rbd);
StopWatch sw = new StopWatch();
sw.start("prototype");
for (int i = 0; i < 100000; i++) {
TestBean tb = (TestBean) lbf.getBean("test");
assertEquals("juergen", tb.getName());
assertEquals(99, tb.getAge());
}
sw.stop();
// System.out.println(sw.getTotalTimeMillis());
assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 3000);
}
private long testBeforeAdviceWithoutJoinPoint(String file, int howmany, String technology) {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file, CLASS);
StopWatch sw = new StopWatch();
sw.start(howmany + " repeated before advice invocations with " + technology);
ITestBean adrian = (ITestBean) bf.getBean("adrian");
assertTrue(AopUtils.isAopProxy(adrian));
Advised a = (Advised) adrian;
assertTrue(a.getAdvisors().length >= 3);
assertEquals("adrian", adrian.getName());
for (int i = 0; i < howmany; i++) {
adrian.getName();
}
sw.stop();
System.out.println(sw.prettyPrint());
return sw.getLastTaskTimeMillis();
}
@Test
public void testAspectsAndAdvisorAppliedToPrototypeIsFastEnough() {
Assume.group(TestGroup.PERFORMANCE);
Assume.notLogging(factoryLog);
ClassPathXmlApplicationContext ac = newContext("aspectsPlusAdvisor.xml");
StopWatch sw = new StopWatch();
sw.start("Prototype Creation");
for (int i = 0; i < 10000; i++) {
ITestBean shouldBeWeaved = (ITestBean) ac.getBean("adrian2");
if (i < 10) {
doTestAspectsAndAdvisorAreApplied(ac, shouldBeWeaved);
}
}
sw.stop();
// What's a reasonable expectation for _any_ server or developer machine load?
// 9 seconds?
assertStopWatchTimeLimit(sw, 9000);
}
@Test
public void testPrototypeCreationWithOverriddenAutowiredPropertiesIsFastEnough() {
GenericApplicationContext ctx = new GenericApplicationContext();
AnnotationConfigUtils.registerAnnotationConfigProcessors(ctx);
ctx.refresh();
RootBeanDefinition rbd = new RootBeanDefinition(AutowiredAnnotatedTestBean.class);
rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
rbd.getPropertyValues().add("spouse", new RuntimeBeanReference("spouse"));
ctx.registerBeanDefinition("test", rbd);
ctx.registerBeanDefinition("spouse", new RootBeanDefinition(TestBean.class));
TestBean spouse = (TestBean) ctx.getBean("spouse");
StopWatch sw = new StopWatch();
sw.start("prototype");
for (int i = 0; i < 100000; i++) {
TestBean tb = (TestBean) ctx.getBean("test");
assertSame(spouse, tb.getSpouse());
}
sw.stop();
assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 6000);
}
@Override
protected Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable {
String name = createInvocationTraceName(invocation);
StopWatch stopWatch = new StopWatch(name);
stopWatch.start(name);
try {
return invocation.proceed();
}
finally {
stopWatch.stop();
writeToLog(logger, stopWatch.shortSummary());
}
}
protected void printSelectTaskMonitorLog(StopWatch clock, int size, boolean resultFlag) {
clock.stop();
getMonitorLogger().info(MONITOR_LOGGER_PATTERN_SELECT_TASKS,
jobConfig.getSysCode(),
jobConfig.getTaskName(),
jobConfig.getBeanName(),
ContextLog4j2Util.getRequestNo(),
RpcContext.getContext().getRemoteHost(),
size,
resultFlag ? Response.SUCC : Response.FAIL, clock.getTotalTimeMillis());
}
@Test
public void testGetStringParameterWithDefaultValueHandlingIsFastEnough() {
Assume.group(TestGroup.PERFORMANCE);
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.getStringParameter(request, "nonExistingParam", "defaultValue");
}
sw.stop();
assertThat(sw.getTotalTimeMillis(), lessThan(250L));
}
/**
* 搜索文件
*
* @author: quhailong
* @date: 2019/9/24
*/
//@RequestMapping(value = "search", method = {RequestMethod.POST})
@RequestMapping(value = "searchfile", method = RequestMethod.GET)
public RestAPIResult<String> searchFile(SearchFileRequest request) {
logger.info("搜索文件请求URL:{}", httpServletRequest.getRequestURL());
StopWatch stopWatch = new StopWatch();
stopWatch.start();
logger.info("搜索文件数据处理开始,request:{}", request);
RestAPIResult<String> result = queryContentProvider.searchFileHandle(request);
logger.info("搜索文件数据处理结束,result:{}", result);
stopWatch.stop();
logger.info("搜索文件调用时间,millies:{}", stopWatch.getTotalTimeMillis());
return result;
}
protected void initDb() throws LiquibaseException {
StopWatch watch = new StopWatch();
watch.start();
super.afterPropertiesSet();
watch.stop();
log.debug("Started Liquibase in {} ms", watch.getTotalTimeMillis());
}
protected void initDb() throws LiquibaseException {
StopWatch watch = new StopWatch();
watch.start();
super.afterPropertiesSet();
watch.stop();
log.debug("Started Liquibase in {} ms", watch.getTotalTimeMillis());
}
@Test
public void parseSmallData() throws Exception {
// Warm up
sp.process(new FileReader("src/test/resources/xml/small/InterchangeSection.xml"));
StopWatch sw = new StopWatch();
sw.start();
sp.process(new FileReader("src/test/resources/xml/small/InterchangeSectionBig.xml"));
sw.stop();
// LOG.info("Total time: "+sw.getTotalTimeMillis());
}
/**
* 下载文件
*
* @author: quhailong
* @date: 2019/9/25
*/
//@RequestMapping(value = "/download", method = RequestMethod.POST)
@RequestMapping(value = "download", method = RequestMethod.GET)
public void download(String uid, String vids, HttpServletResponse res) throws IOException {
logger.info("下载文件请求URL:{}", httpServletRequest.getRequestURL());
StopWatch stopWatch = new StopWatch();
stopWatch.start();
logger.info("下载文件数据处理开始,vids:{}", vids);
downloadProvider.downloadHandle(uid, vids, res);
logger.info("下载文件数据处理结束");
stopWatch.stop();
logger.info("下载文件调用时间,millies:{}", stopWatch.getTotalTimeMillis());
}
/**
* 生成验证码
*
* @author: quhailong
* @date: 2019/9/26
*/
@RequestMapping(value = "getverfyimg/{vcodestr}", method = RequestMethod.GET)
public void getVerfyImg(@PathVariable(value = "vcodestr") String vcodestr, HttpServletResponse response) {
logger.info("生成验证码请求URL:{}", httpServletRequest.getRequestURL());
StopWatch stopWatch = new StopWatch();
stopWatch.start();
logger.info("生成验证码数据处理开始");
edgeServiceProvider.getVerfyImgHandle(vcodestr, response);
logger.info("生成验证码数据处理结束");
stopWatch.stop();
logger.info("生成验证码调用时间,millies:{}", stopWatch.getTotalTimeMillis());
}
@After("anyMethod()")
public void after(JoinPoint point) {
StopWatch watch = threadLocal.get();
Object[] args = point.getArgs();
String methodName = point.getSignature().getName();
ShardingContext context = (ShardingContext) args[0];
watch.stop();
if (null != context) {
logger.info("current job {}->{} completed used : {} ms", context.getJobName(), methodName,
watch.getTotalTimeMillis());
}
threadLocal.remove();
}
@Bean
public Docket swaggerSpringfoxDocket(PkmstProperties pkmstProperties) {
StopWatch watch = new StopWatch();
watch.start();
Contact contact = new Contact(
pkmstProperties.getSwagger().getContactName(),
pkmstProperties.getSwagger().getContactUrl(),
pkmstProperties.getSwagger().getContactEmail());
ApiInfo apiInfo = new ApiInfo(
pkmstProperties.getSwagger().getTitle(),
pkmstProperties.getSwagger().getDescription(),
pkmstProperties.getSwagger().getVersion(),
pkmstProperties.getSwagger().getTermsOfServiceUrl(),
contact,
pkmstProperties.getSwagger().getLicense(),
pkmstProperties.getSwagger().getLicenseUrl());
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.forCodeGeneration(true)
.genericModelSubstitutes(ResponseEntity.class)
.ignoredParameterTypes(java.sql.Date.class)
.directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
.directModelSubstitute(java.time.LocalDateTime.class, Date.class)
.select()
.apis(RequestHandlerSelectors.basePackage("com.prokarma.pkmst"))
// .paths(regex(DEFAULT_INCLUDE_PATTERN))
.paths(PathSelectors.any())
.build();
watch.stop();
return docket;
}
/**
* 获取分享用户信息
*
* @author: quhailong
* @date: 2019/9/26
*/
//@RequestMapping(value = "getShareUser", method = {RequestMethod.POST})
@RequestMapping(value = "getshareuser", method = RequestMethod.GET)
public RestAPIResult<String> getShareUser(String shareId) {
logger.info("获取分享用户信息请求URL:{}", httpServletRequest.getRequestURL());
StopWatch stopWatch = new StopWatch();
stopWatch.start();
logger.info("获取分享用户信息数据处理开始,shareId:{}", shareId);
RestAPIResult<String> result = shareProvider.getShareUserHandle(shareId);
logger.info("获取分享用户信息数据处理结束,result:{}", result);
stopWatch.stop();
logger.info("获取分享用户信息调用时间,millies:{}", stopWatch.getTotalTimeMillis());
return result;
}