org.springframework.util.StopWatch类的使用及代码示例

x33g5p2x  于2022-01-30 转载在 其他  
字(10.3k)|赞(0)|评价(0)|浏览(162)

本文整理了Java中org.springframework.util.StopWatch类的一些代码示例,展示了StopWatch类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。StopWatch类的具体详情如下:
包路径:org.springframework.util.StopWatch
类名称:StopWatch

StopWatch介绍

[英]Simple stop watch, allowing for timing of a number of tasks, exposing total running time and running time for each named task.

Conceals use of System.currentTimeMillis(), improving the readability of application code and reducing the likelihood of calculation errors.

Note that this object is not designed to be thread-safe and does not use synchronization.

This class is normally used to verify performance during proof-of-concepts and in development, rather than as part of production applications.
[中]简单的秒表,允许对许多任务进行计时,显示每个指定任务的总运行时间和运行时间。
隐藏System.currentTimeMillis()的使用,提高应用程序代码的可读性,降低计算错误的可能性。
请注意,此对象不是为线程安全而设计的,并且不使用同步。
该类通常用于在概念验证和开发过程中验证性能,而不是作为生产应用程序的一部分。

代码示例

代码示例来源:origin: spring-projects/spring-framework

private long testRepeatedAroundAdviceInvocations(String file, int howmany, String technology) {
  ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file, CLASS);
  StopWatch sw = new StopWatch();
  sw.start(howmany + " repeated around advice invocations with " + technology);
  ITestBean adrian = (ITestBean) bf.getBean("adrian");
  assertTrue(AopUtils.isAopProxy(adrian));
  assertEquals(68, adrian.getAge());
  for (int i = 0; i < howmany; i++) {
    adrian.getAge();
  }
  sw.stop();
  System.out.println(sw.prettyPrint());
  return sw.getLastTaskTimeMillis();
}

代码示例来源:origin: spring-projects/spring-framework

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));
    if (stopWatch.isRunning()) {
      stopWatch.stop();
        this.exceptionMessage, invocation, null, ex, stopWatch.getTotalTimeMillis()), ex);
    throw ex;
      if (stopWatch.isRunning()) {
        stopWatch.stop();
          this.exitMessage, invocation, returnValue, null, stopWatch.getTotalTimeMillis()));

代码示例来源:origin: spring-projects/spring-framework

/**
 * Return a short description of the total running time.
 */
public String shortSummary() {
  return "StopWatch '" + getId() + "': running time (millis) = " + getTotalTimeMillis();
}

代码示例来源:origin: spring-projects/spring-framework

@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());
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testPerformance1() {
  Assume.group(TestGroup.PERFORMANCE);
  StopWatch watch = new StopWatch("integer->string conversionPerformance");
  watch.start("convert 4,000,000 with conversion service");
  for (int i = 0; i < 4000000; i++) {
    conversionService.convert(3, String.class);
  }
  watch.stop();
  watch.start("convert 4,000,000 manually");
  for (int i = 0; i < 4000000; i++) {
    Integer.valueOf(3).toString();
  }
  watch.stop();
  // System.out.println(watch.prettyPrint());
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public final void stop() {
  synchronized (this.lifecycleMonitor) {
    if (isRunning()) {
      String serverName = getClass().getSimpleName();
      logger.debug("Stopping " + serverName + "...");
      this.running = false;
      try {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        stopInternal();
        logger.debug("Server stopped (" + stopWatch.getTotalTimeMillis() + " millis).");
      }
      catch (Throwable ex) {
        throw new IllegalStateException(ex);
      }
      finally {
        reset();
      }
    }
  }
}

代码示例来源:origin: dsyer/spring-boot-aspectj

@Around("execution(private * org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.postProcessBeforeInitialization(Object, String, ..)) && args(bean,..)")
public Object bind(ProceedingJoinPoint joinPoint, Object bean) throws Throwable {
  bind.start();
  Object result = joinPoint.proceed();
  bind.stop();
  logger.info("Bind,," + bean.getClass().getName() + ": "
      + bind.getLastTaskTimeMillis());
  return result;
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void validUsage() throws Exception {
  String id = "myId";
  StopWatch sw = new StopWatch(id);
  long int1 = 166L;
  long int2 = 45L;
  assertFalse(sw.isRunning());
  sw.start(name1);
  Thread.sleep(int1);
  assertTrue(sw.isRunning());
  assertEquals(name1, sw.currentTaskName());
  sw.stop();
  sw.start(name2);
  Thread.sleep(int2);
  sw.stop();
  assertTrue(sw.getTaskCount() == 2);
  String pp = sw.prettyPrint();
  assertTrue(pp.contains(name1));
  assertTrue(pp.contains(name2));
  StopWatch.TaskInfo[] tasks = sw.getTaskInfo();
  assertTrue(tasks.length == 2);
  assertTrue(tasks[0].getTaskName().equals(name1));
  assertTrue(tasks[1].getTaskName().equals(name2));
  String toString = sw.toString();
  assertTrue(toString.contains(id));

代码示例来源:origin: spring-projects/spring-framework

@Test
public void validUsageNotKeepingTaskList() throws Exception {
  sw.setKeepTaskList(false);
  long int1 = 166L;
  long int2 = 45L;
  String name2 = "Task 2";
  assertFalse(sw.isRunning());
  sw.start(name1);
  Thread.sleep(int1);
  assertTrue(sw.isRunning());
  sw.stop();
  sw.start(name2);
  Thread.sleep(int2);
  sw.stop();
  assertTrue(sw.getTaskCount() == 2);
  String pp = sw.prettyPrint();
  assertTrue(pp.contains("kept"));
  String toString = sw.toString();
  assertFalse(toString.contains(name1));
  assertFalse(toString.contains(name2));
  sw.getTaskInfo();

代码示例来源:origin: spring-projects/spring-framework

@Test
public void rejectsStartTwice() {
  sw.start("");
  sw.stop();
  sw.start("");
  assertTrue(sw.isRunning());
  exception.expect(IllegalStateException.class);
  sw.start("");
}

代码示例来源:origin: kloiasoft/eventapis

@Override
boolean runInternal(StopWatch stopWatch) {
  stopWatch.start("collectEndOffsets");
  List<TopicPartition> collect = topicsMap.entrySet().stream().flatMap(
      topic -> topic.getValue().getPartitions().values().stream().map(partition -> new TopicPartition(topic.getKey(), partition.getNumber()))
  ).collect(Collectors.toList());
  java.util.Map<TopicPartition, Long> map = kafkaConsumer.endOffsets(collect);
  java.util.Map<String, List<Partition>> result = new HashMap<>();
  map.forEach((topicPartition, endOffset) -> {
    if (!result.containsKey(topicPartition.topic()))
      result.put(topicPartition.topic(), new ArrayList<>());
    result.get(topicPartition.topic()).add(new Partition(topicPartition.partition(), endOffset));
  });
  result.forEach((topic, endOffset) -> topicsMap.executeOnKey(topic, new EndOffsetSetter(endOffset)));
  log.debug("collectEndOffsets:" + result.toString());
  stopWatch.stop();
  log.debug("TopicEndOffsetSchedule:" + topicsMap.entrySet());
  log.debug(stopWatch.prettyPrint());
  return true;
}

代码示例来源:origin: spring-projects/spring-integration-samples

@Override
public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
  StopWatchHolder holder = this.stopWatchHolder.get();
  if (holder != null) {
    holder.getStopWatch().stop();
    Stats stats = this.statsMap.get(holder.getType());
    if (stats == null) {
      stats = this.statsMap.get(Object.class);
    }
    stats.add(holder.getStopWatch().getLastTaskTimeMillis());
  }
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Start an unnamed task. The results are undefined if {@link #stop()}
 * or timing methods are called without invoking this method.
 * @see #stop()
 */
public void start() throws IllegalStateException {
  start("");
}

代码示例来源:origin: kloiasoft/eventapis

@Override
boolean runInternal(StopWatch stopWatch) throws InterruptedException, ExecutionException {
  stopWatch.start("adminClient.listTopics()");
  Collection<String> topicNames = adminClient.listTopics().listings().get()
      .stream().map(TopicListing::name).filter(this::shouldCollectEvent).collect(Collectors.toList());
  topicsMap.removeAll(new RemoveTopicPredicate(topicNames));
  DescribeTopicsResult describeTopicsResult = adminClient.describeTopics(topicNames);
  describeTopicsResult.all().get().forEach(
      (topic, topicDescription) -> topicsMap.executeOnKey(topic, new SetTopicPartitionsProcessor(
          topicDescription.partitions().stream().map(TopicPartitionInfo::partition).collect(Collectors.toList()))
      )
  );
  metaMap.set(this.getName() + TopicServiceScheduler.LAST_SUCCESS_PREFIX, System.currentTimeMillis());
  log.debug("Topics:" + topicsMap.entrySet());
  log.debug(stopWatch.prettyPrint());
  return true;
}

代码示例来源:origin: kloiasoft/eventapis

@Override
public void run() {
  StopWatch stopWatch = new StopWatch();
  boolean isSuccess;
  try {
    isSuccess = runInternal(stopWatch);
    if (isSuccess) {
      metaMap.set(getLastSuccessKey(), System.currentTimeMillis());
    }
  } catch (InterruptedException | ExecutionException e) {
    log.warn("Error While trying to run ScheduledTask: " + e.getMessage(), e);
  }
  log.debug(stopWatch.prettyPrint());
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void failureToStartBeforeStop() {
  exception.expect(IllegalStateException.class);
  sw.stop();
}

代码示例来源:origin: spring-projects/spring-framework

private void assertStopWatchTimeLimit(final StopWatch sw, final long maxTimeMillis) {
  long totalTimeMillis = sw.getTotalTimeMillis();
  assertTrue("'" + sw.getLastTaskName() + "' took too long: expected less than<" + maxTimeMillis +
      "> ms, actual<" + totalTimeMillis + "> ms.", totalTimeMillis < maxTimeMillis);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
@Ignore("Intended for use during development only")
public void shouldBeFasterThanSynchronizedMap() throws InterruptedException {
  Map<Integer, WeakReference<String>> synchronizedMap = Collections.synchronizedMap(new WeakHashMap<Integer, WeakReference<String>>());
  StopWatch mapTime = timeMultiThreaded("SynchronizedMap", synchronizedMap, v -> new WeakReference<>(String.valueOf(v)));
  System.out.println(mapTime.prettyPrint());
  this.map.setDisableTestHooks(true);
  StopWatch cacheTime = timeMultiThreaded("WeakConcurrentCache", this.map, String::valueOf);
  System.out.println(cacheTime.prettyPrint());
  // We should be at least 4 time faster
  assertThat(cacheTime.getTotalTimeSeconds(), is(lessThan(mapTime.getTotalTimeSeconds() / 4.0)));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void failureToStartBeforeGettingTimings() {
  exception.expect(IllegalStateException.class);
  sw.getLastTaskTimeMillis();
}

代码示例来源:origin: net.oschina.zcx7878/cicada.boot-web

StringBuffer getEnd(StringBuffer sb, StopWatch sw)
  {
    sb.insert(0, "\r\n" + sw.prettyPrint());
    sb.append("\r\n");
    sb.append("-----------------------------------------");
    return sb;
  }
}

相关文章