下面列出了org.springframework.util.StopWatch#start ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testGetValuePerformance() throws Exception {
Assume.group(TestGroup.PERFORMANCE);
Map<String, String> map = new HashMap<>();
map.put("key", "value");
EvaluationContext context = new StandardEvaluationContext(map);
ExpressionParser spelExpressionParser = new SpelExpressionParser();
Expression expr = spelExpressionParser.parseExpression("#root['key']");
StopWatch s = new StopWatch();
s.start();
for (int i = 0; i < 10000; i++) {
expr.getValue(context);
}
s.stop();
assertThat(s.getTotalTimeMillis(), lessThan(200L));
}
@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);
}
@Test
public void testPerformance2() throws Exception {
Assume.group(TestGroup.PERFORMANCE);
StopWatch watch = new StopWatch("list<string> -> list<integer> conversionPerformance");
watch.start("convert 4,000,000 with conversion service");
List<String> source = new LinkedList<String>();
source.add("1");
source.add("2");
source.add("3");
TypeDescriptor td = new TypeDescriptor(getClass().getField("list"));
for (int i = 0; i < 1000000; i++) {
conversionService.convert(source, TypeDescriptor.forObject(source), td);
}
watch.stop();
watch.start("convert 4,000,000 manually");
for (int i = 0; i < 4000000; i++) {
List<Integer> target = new ArrayList<Integer>(source.size());
for (String element : source) {
target.add(Integer.valueOf(element));
}
}
watch.stop();
// System.out.println(watch.prettyPrint());
}
@Test
public void testPrototypeCreationWithDependencyCheckIsFastEnough() {
Assume.group(TestGroup.PERFORMANCE);
Assume.notLogging(factoryLog);
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(LifecycleBean.class);
rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
rbd.setDependencyCheck(RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
lbf.registerBeanDefinition("test", rbd);
lbf.addBeanPostProcessor(new LifecycleBean.PostProcessor());
lbf.freezeConfiguration();
StopWatch sw = new StopWatch();
sw.start("prototype");
for (int i = 0; i < 100000; i++) {
lbf.getBean("test");
}
sw.stop();
// System.out.println(sw.getTotalTimeMillis());
assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 3000);
}
@Test
public void testAspectsAndAdvisorNotAppliedToManySingletonsIsFastEnough() {
Assume.group(TestGroup.PERFORMANCE);
Assume.notLogging(factoryLog);
GenericApplicationContext ac = new GenericApplicationContext();
new XmlBeanDefinitionReader(ac).loadBeanDefinitions(new ClassPathResource(qName("aspectsPlusAdvisor.xml"),
getClass()));
for (int i = 0; i < 10000; i++) {
ac.registerBeanDefinition("singleton" + i, new RootBeanDefinition(NestedTestBean.class));
}
StopWatch sw = new StopWatch();
sw.start("Singleton Creation");
ac.refresh();
sw.stop();
// What's a reasonable expectation for _any_ server or developer machine load?
// 8 seconds?
assertStopWatchTimeLimit(sw, 8000);
}
@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);
}
@Test
public void testGetValuePerformance() throws Exception {
Assume.group(TestGroup.PERFORMANCE);
Map<String, String> map = new HashMap<String, String>();
map.put("key", "value");
EvaluationContext context = new StandardEvaluationContext(map);
ExpressionParser spelExpressionParser = new SpelExpressionParser();
Expression expr = spelExpressionParser.parseExpression("#root['key']");
StopWatch s = new StopWatch();
s.start();
for (int i = 0; i < 10000; i++) {
expr.getValue(context);
}
s.stop();
assertThat(s.getTotalTimeMillis(), lessThan(200L));
}
@Test
public void testPerformance2() throws Exception {
Assume.group(TestGroup.PERFORMANCE);
StopWatch watch = new StopWatch("list<string> -> list<integer> conversionPerformance");
watch.start("convert 4,000,000 with conversion service");
List<String> source = new LinkedList<>();
source.add("1");
source.add("2");
source.add("3");
TypeDescriptor td = new TypeDescriptor(getClass().getField("list"));
for (int i = 0; i < 1000000; i++) {
conversionService.convert(source, TypeDescriptor.forObject(source), td);
}
watch.stop();
watch.start("convert 4,000,000 manually");
for (int i = 0; i < 4000000; i++) {
List<Integer> target = new ArrayList<>(source.size());
for (String element : source) {
target.add(Integer.valueOf(element));
}
}
watch.stop();
// System.out.println(watch.prettyPrint());
}
/**
* Writes a log message before the invocation based on the value of {@code enterMessage}.
* If the invocation succeeds, then a log message is written on exit based on the value
* {@code exitMessage}. If an exception occurs during invocation, then a message is
* written based on the value of {@code exceptionMessage}.
* @see #setEnterMessage
* @see #setExitMessage
* @see #setExceptionMessage
*/
@Override
protected Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable {
String name = ClassUtils.getQualifiedMethodName(invocation.getMethod());
StopWatch stopWatch = new StopWatch(name);
Object returnValue = null;
boolean exitThroughException = false;
try {
stopWatch.start(name);
writeToLog(logger,
replacePlaceholders(this.enterMessage, invocation, null, null, -1));
returnValue = invocation.proceed();
return returnValue;
}
catch (Throwable ex) {
if (stopWatch.isRunning()) {
stopWatch.stop();
}
exitThroughException = true;
writeToLog(logger, replacePlaceholders(
this.exceptionMessage, invocation, null, ex, stopWatch.getTotalTimeMillis()), ex);
throw ex;
}
finally {
if (!exitThroughException) {
if (stopWatch.isRunning()) {
stopWatch.stop();
}
writeToLog(logger, replacePlaceholders(
this.exitMessage, invocation, returnValue, null, stopWatch.getTotalTimeMillis()));
}
}
}
@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;
}
@Test
public void prototypeCreationIsFastEnough() {
Assume.group(TestGroup.PERFORMANCE);
Assume.notLogging(factoryLog);
GenericApplicationContext ac = new GenericApplicationContext();
RootBeanDefinition rbd = new RootBeanDefinition(TestBean.class);
rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
rbd.getConstructorArgumentValues().addGenericArgumentValue("#{systemProperties.name}");
rbd.getPropertyValues().add("country", "#{systemProperties.country}");
ac.registerBeanDefinition("test", rbd);
ac.refresh();
StopWatch sw = new StopWatch();
sw.start("prototype");
System.getProperties().put("name", "juergen");
System.getProperties().put("country", "UK");
try {
for (int i = 0; i < 100000; i++) {
TestBean tb = (TestBean) ac.getBean("test");
assertEquals("juergen", tb.getName());
assertEquals("UK", tb.getCountry());
}
sw.stop();
}
finally {
System.getProperties().remove("country");
System.getProperties().remove("name");
}
assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 6000);
}
/**
* 上传用户头像
*
* @author: quhailong
* @date: 2019/9/26
*/
//@RequestMapping(value = "api/uploadPic", method = { RequestMethod.POST })
@RequestMapping(value = "uploadpic", method = RequestMethod.POST)
public RestAPIResult<String> uploadPic(@RequestParam("uid") String uid, @RequestParam("file") MultipartFile file) throws IOException {
logger.info("上传用户头像请求URL:{}", httpServletRequest.getRequestURL());
StopWatch stopWatch = new StopWatch();
stopWatch.start();
logger.info("上传用户头像数据处理开始,uid:{}", uid);
RestAPIResult<String> result = registProvider.uploadPicHandle(uid, file);
logger.info("上传用户头像数据处理结束,result:{}", result);
stopWatch.stop();
logger.info("上传用户头像调用时间,millies:{}", stopWatch.getTotalTimeMillis());
return result;
}
/**
* 手机号查重
*
* @author: quhailong
* @date: 2019/9/25
*/
@RequestMapping(value = "regcheckphone", method = RequestMethod.GET)
public RestAPIResult<String> checkPhone(@RequestParam("phoneNum") String phoneNum) {
logger.info("手机号查重请求URL:{}", httpServletRequest.getRequestURL());
StopWatch stopWatch = new StopWatch();
stopWatch.start();
logger.info("手机号查重数据处理开始,phoneNum:{}", phoneNum);
RestAPIResult<String> result = registProvider.checkPhoneHandle(phoneNum);
logger.info("手机号查重数据处理结束,result:{}", result);
stopWatch.stop();
logger.info("手机号查重调用时间,millies:{}", stopWatch.getTotalTimeMillis());
return result;
}
@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());
}
}
@Test
public void testGetLongParameterWithDefaultValueHandlingIsFastEnough() {
Assume.group(TestGroup.PERFORMANCE);
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.getLongParameter(request, "nonExistingParam", 0);
}
sw.stop();
assertThat(sw.getTotalTimeMillis(), lessThan(250L));
}
@Test
public void setPrimitiveArrayPropertyLargeMatching() {
Assume.group(TestGroup.PERFORMANCE);
Assume.notLogging(LogFactory.getLog(AbstractPropertyAccessorTests.class));
PrimitiveArrayBean target = new PrimitiveArrayBean();
AbstractPropertyAccessor accessor = createAccessor(target);
int[] input = new int[1024];
StopWatch sw = new StopWatch();
sw.start("array1");
for (int i = 0; i < 1000; i++) {
accessor.setPropertyValue("array", input);
}
sw.stop();
assertEquals(1024, target.getArray().length);
assertEquals(0, target.getArray()[0]);
long time1 = sw.getLastTaskTimeMillis();
assertTrue("Took too long", sw.getLastTaskTimeMillis() < 100);
accessor.registerCustomEditor(String.class, new StringTrimmerEditor(false));
sw.start("array2");
for (int i = 0; i < 1000; i++) {
accessor.setPropertyValue("array", input);
}
sw.stop();
assertTrue("Took too long", sw.getLastTaskTimeMillis() < 125);
accessor.registerCustomEditor(int.class, "array.somePath", new CustomNumberEditor(Integer.class, false));
sw.start("array3");
for (int i = 0; i < 1000; i++) {
accessor.setPropertyValue("array", input);
}
sw.stop();
assertTrue("Took too long", sw.getLastTaskTimeMillis() < 100);
accessor.registerCustomEditor(int.class, "array[0].somePath", new CustomNumberEditor(Integer.class, false));
sw.start("array3");
for (int i = 0; i < 1000; i++) {
accessor.setPropertyValue("array", input);
}
sw.stop();
assertTrue("Took too long", sw.getLastTaskTimeMillis() < 100);
accessor.registerCustomEditor(int.class, new CustomNumberEditor(Integer.class, false));
sw.start("array4");
for (int i = 0; i < 100; i++) {
accessor.setPropertyValue("array", input);
}
sw.stop();
assertEquals(1024, target.getArray().length);
assertEquals(0, target.getArray()[0]);
assertTrue("Took too long", sw.getLastTaskTimeMillis() > time1);
}
public void beforeJob(JobExecution jobExecution) {
stopWatch = new StopWatch();
stopWatch.start("Processing image submissions");
}
/**
* @param applicationName
* @param from
* @param to
* @param limit max number of data return. if the requested data exceed this limit, we need additional calls to
* fetch the rest of the data
* @return
*/
@RequestMapping(value = "/getScatterData", method = RequestMethod.GET)
@ResponseBody
public ScatterView.ResultView getScatterData(
@RequestParam("application") String applicationName,
@RequestParam("from") long from,
@RequestParam("to") long to,
@RequestParam("xGroupUnit") int xGroupUnit,
@RequestParam("yGroupUnit") int yGroupUnit,
@RequestParam("limit") int limit,
@RequestParam(value = "backwardDirection", required = false, defaultValue = "true") boolean backwardDirection,
@RequestParam(value = "filter", required = false) String filterText) {
if (xGroupUnit <= 0) {
throw new IllegalArgumentException("xGroupUnit(" + xGroupUnit + ") must be positive number");
}
if (yGroupUnit < 0) {
throw new IllegalArgumentException("yGroupUnit(" + yGroupUnit + ") may not be negative number");
}
limit = LimitUtils.checkRange(limit);
StopWatch watch = new StopWatch();
watch.start("getScatterData");
// TODO range check verification exception occurs. "from" is bigger than "to"
final Range range = Range.newUncheckedRange(from, to);
logger.debug("fetch scatter data. RANGE={}, X-Group-Unit:{}, Y-Group-Unit:{}, LIMIT={}, BACKWARD_DIRECTION:{}, FILTER:{}", range, xGroupUnit, yGroupUnit, limit, backwardDirection, filterText);
ScatterView.DotView dotView;
if (StringUtils.isEmpty(filterText)) {
dotView = selectScatterData(applicationName, range, xGroupUnit, Math.max(yGroupUnit, 1), limit, backwardDirection);
} else {
dotView = selectFilterScatterData(applicationName, range, xGroupUnit, Math.max(yGroupUnit, 1), limit, backwardDirection, filterText);
}
ScatterView.Status status = new ScatterView.Status(System.currentTimeMillis(), range);
watch.stop();
if (logger.isDebugEnabled()) {
logger.debug("Fetch scatterData time : {}ms", watch.getLastTaskTimeMillis());
}
return ScatterView.wrapResult(dotView, status);
}
@Override
public boolean execute(String jobName, Date jobRunDate) {
StopWatch stopWatch = new StopWatch();
stopWatch.start(jobName);
String filePath = batchFileDirectoryName + File.separator;
List<String> fileNameList = new ArrayList<String>();
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.NIGHTLY_OUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.COLLECTOR_SCRUBBER_INPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.COLLECTOR_SCRUBBER_VALID_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.COLLECTOR_SCRUBBER_ERROR_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.COLLECTOR_SCRUBBER_EXPIRED_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.COLLECTOR_SCRUBBER_ERROR_SORTED_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.BACKUP_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.PRE_SCRUBBER_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.SCRUBBER_INPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.SCRUBBER_VALID_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.SCRUBBER_ERROR_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.SCRUBBER_EXPIRED_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.SCRUBBER_ERROR_SORTED_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.DEMERGER_VAILD_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.DEMERGER_ERROR_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.POSTER_INPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.REVERSAL_POSTER_VALID_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.REVERSAL_POSTER_ERROR_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.POSTER_VALID_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.POSTER_ERROR_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.ICR_TRANSACTIONS_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.ICR_POSTER_INPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.ICR_POSTER_ERROR_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.ICR_ENCUMBRANCE_OUTPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.ICR_ENCUMBRANCE_POSTER_INPUT_FILE);
fileNameList.add(GeneralLedgerConstants.BatchFileSystem.ICR_ENCUMBRANCE_POSTER_ERROR_OUTPUT_FILE);
for (String fileName : fileNameList){
File file = new File(filePath + fileName + GeneralLedgerConstants.BatchFileSystem.EXTENSION);
if (file.exists()) {
String changedFileName = filePath + fileName + "." + getDateTimeService().toDateTimeStringForFilename(jobRunDate);
file.renameTo(new File(changedFileName + GeneralLedgerConstants.BatchFileSystem.EXTENSION));
}
}
stopWatch.stop();
if (LOG.isDebugEnabled()) {
LOG.debug("FileRenameStep of " + jobName + " took " + (stopWatch.getTotalTimeSeconds() / 60.0) + " minutes to complete");
}
return true;
}