本文整理汇总了Java中org.apache.commons.lang3.time.StopWatch.getTime方法的典型用法代码示例。如果您正苦于以下问题:Java StopWatch.getTime方法的具体用法?Java StopWatch.getTime怎么用?Java StopWatch.getTime使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.commons.lang3.time.StopWatch
的用法示例。
在下文中一共展示了StopWatch.getTime方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: monitorElapsedTime
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
/**
* Monitor the elapsed time of method on controller layer, in
* order to detect performance problems as soon as possible.
* If elapsed time > 1 s, log it as an error. Otherwise, log it
* as an info.
*/
@Around("controllerLayer()")
public Object monitorElapsedTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
// Timing the method in controller layer
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object result = proceedingJoinPoint.proceed();
stopWatch.stop();
// Log the elapsed time
double elapsedTime = stopWatch.getTime() / 1000.0;
Signature signature = proceedingJoinPoint.getSignature();
String infoString = "[" + signature.toShortString() + "][Elapsed time: " + elapsedTime + " s]";
if (elapsedTime > 1) {
log.error(infoString + "[Note that it's time consuming!]");
} else {
log.info(infoString);
}
// Return the result
return result;
}
示例2: getResponseFromPrimedContext
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
@Test // primed, got
// 30_000, 1,000
// naive,loop 100, 10
// map, linear insert 100, 6
// map, get on insert 0.1, 0.005
public void getResponseFromPrimedContext() {
final StopWatch stopWatch = new StopWatch();
stopWatch.start();
primings.forEach(primingContext::add);
stopWatch.stop();
long time = stopWatch.getTime();
System.out.println(time + " ms elapsed inserting " + primings.size() + " primings");
stopWatch.reset();
stopWatch.start();
for (int i : indices) {
final AppRequest request = primings.get(i).getAppRequest();
primingContext.getResponse(request).get();
}
time = stopWatch.getTime();
System.out.println(time + " ms elapsed getting " + indices.size() + " requests");
}
示例3: execute
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
public void execute() throws Exception{
StopWatch stopWatch = new StopWatch();
stopWatch.start();
long initm=Runtime.getRuntime().freeMemory();
process();
stopWatch.stop();
long timeSpent = stopWatch.getTime();
long endm=Runtime.getRuntime().freeMemory();
this.getSlot().addStep(nodeId);
//性能统计
CompStatistics statistics = new CompStatistics();
statistics.setComponentClazzName(this.getClass().getSimpleName());
statistics.setTimeSpent(timeSpent);
statistics.setMemorySpent(initm-endm);
MonitorBus.addStatistics(statistics);
if(this instanceof NodeCondComponent){
String condNodeId = this.getSlot().getCondResult(this.getClass().getName());
if(StringUtils.isNotBlank(condNodeId)){
Node thisNode = FlowParser.getNode(nodeId);
Node condNode = thisNode.getCondNode(condNodeId);
if(condNode != null){
NodeComponent condComponent = condNode.getInstance();
condComponent.setSlotIndex(slotIndexTL.get());
condComponent.execute();
}
}
}
LOG.debug("componnet[{}] finished in {} milliseconds",this.getClass().getSimpleName(),timeSpent);
}
示例4: perfTest
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
@Ignore
@Test
public void perfTest() throws IOException, MkvElementVisitException, InterruptedException {
final byte [] inputBytes = TestResourceUtil.getTestInputByteArray("output_get_media.mkv");
int numIterations = 1000;
StopWatch timer = new StopWatch();
timer.start();
for (int i = 0; i < numIterations; i++) {
try (ByteArrayInputStream in = new ByteArrayInputStream(inputBytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
OutputSegmentMerger merger =
OutputSegmentMerger.createDefault(outputStream);
StreamingMkvReader mkvStreamReader =
StreamingMkvReader.createWithMaxContentSize(new InputStreamParserByteSource(in), 32000);
while(mkvStreamReader.mightHaveNext()) {
Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable();
if (mkvElement.isPresent()) {
mkvElement.get().accept(merger);
}
}
}
}
timer.stop();
long totalTimeMillis = timer.getTime();
double totalTimeSeconds = totalTimeMillis/(double )TimeUnit.SECONDS.toMillis(1);
double mergeRate = (double )(inputBytes.length)*numIterations/(totalTimeSeconds*1024*1024);
System.out.println("Total time "+totalTimeMillis+" ms "+" Merging rate "+mergeRate+" MB/s");
}
开发者ID:aws,项目名称:amazon-kinesis-video-streams-parser-library,代码行数:31,代码来源:OutputSegmentMergerTest.java
示例5: run
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
@Override
public void run(GraphDatabaseService db) {
StopWatch watch = new StopWatch();
watch.start();
Set<Slice> slices = generateExamples();
watch.stop();
long time = watch.getTime();
System.out.println(String.format("Generate examples using %dms.", time));
try (Transaction tx = db.beginTx()) {
db.findNodes(Label.label(JavaCodeExtractor.METHOD)).stream().forEach(node -> {
String belongTo = (String) node.getProperty(JavaCodeExtractor.METHOD_BELONGTO);
String name = (String) node.getProperty(JavaCodeExtractor.METHOD_NAME);
String params = (String) node.getProperty(JavaCodeExtractor.METHOD_PARAMS);
params = params.replaceAll("final ", "");
params = Stream.of(params.split(",")).map(String::trim).map(s -> s.split(" ")[0]).reduce((a, b) -> a + "," + b).orElse("");
String signature = String.format("%s.%s(%s)", belongTo, name, params);
List<Slice> examples = slices.stream().filter(slice -> slice.getTargetAPIs().stream().map(Object::toString).anyMatch(s -> s.equals(signature))).collect(Collectors.toList());
Clusters clusters = new Clusters(examples);
for (int i = 0; i < clusters.getClusters().size(); i++) {
for (int j = 0; j < EXAMPLE_PER_CLUSTER && j < clusters.getClusters().get(i).size(); j++) {
String example = clusters.getClusters().get(i).get(j).getSlice();
Node exampleNode = db.createNode(Label.label(API_USAGE_EXAMPLE));
exampleNode.setProperty(EXAMPLE_BODY, example);
node.createRelationshipTo(exampleNode, RelationshipType.withName(HAS_EXAMPLE));
}
}
});
tx.success();
}
}
示例6: call
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
@Override
public CommandResponse call() throws Exception {
StopWatch clock = new StopWatch();
clock.start();
String result = this.executorTask.execute(this.command).andReturnResult();
clock.stop();
CommandResponse taskResult = new CommandResponse(profile, command, result, clock.getTime());
return taskResult;
}
示例7: doAfterCompletion
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
@Override
public void doAfterCompletion(HttpServletRequest request,HttpServletResponse response,Object handler,Exception ex){
if (!monitorMessageEntity.getIsShowAfterCompletionLog()){
return;
}
//---------------------------------------------------------------
StopWatch stopWatch = getStopWatch(request);
if (null == stopWatch || stopWatch.isStopped()){
LOGGER.error("stopWatch is null or stopWatch isStopped!!,request info is:{}", RequestUtil.getRequestInfoMapForLog(request));
return;
}
//---------------------------------------------------------------
stopWatch.split();
long splitTime = stopWatch.getSplitTime();
stopWatch.stop();
long time = stopWatch.getTime();
//---------------------------------------------------------------
if (LOGGER.isDebugEnabled()){
LOGGER.debug(
"afterCompletion [{}.{}()], use time:[{}],total time:[{}]",
HandlerMethodUtil.getDeclaringClassSimpleName((HandlerMethod) handler),
HandlerMethodUtil.getHandlerMethodName((HandlerMethod) handler),
formatDuration(splitTime),
formatDuration(time));
}
}
示例8: main
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
public static void main(String[] args) {
StopWatch timer = new StopWatch();
timer.start();
long solution = P47_DistinctPrimeFactors.findFirst();
double seconds = timer.getTime() / 1000.0;
String message = "The first of the first four consecutive integers " +
"to have four distinct prime factors is %,d.\n" +
"Execution took %.1f seconds.\n";
System.out.printf(message, solution, seconds);
}
示例9: viewDoc
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
/**
* This method is called from viewDoc and from ImcmsSetupFilter.handleDocumentUrl only.
*
* @see ImcmsSetupFilter
*/
public static void viewDoc(DocumentDomainObject document, HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
NDC.push("" + document.getId());
try {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
privateGetDoc(document, res, req);
stopWatch.stop();
long renderTime = stopWatch.getTime();
LOG.trace("Rendering document " + document.getId() + " took " + renderTime + "ms.");
} finally {
NDC.pop();
}
}
示例10: stopTimer
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
/**
* Stops named timer.
* @param name name of timer to stop.
* @return time in milliseconds since timer was started.
*/
public long stopTimer(String name) {
StopWatch sw = getStopWatch(name);
sw.stop();
STOP_WATCHES.remove(name);
return sw.getTime();
}
示例11: getNextInterval
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
private int getNextInterval(StopWatch loopTimer) {
int nextInterval;
long loopTime = loopTimer.getTime();
nextInterval = Math.max(0, ((int) (repeatInterval - loopTime)));
loopTimer.reset();
return nextInterval;
}
示例12: execute
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
/**
* Executes the main method. This is public so that client distributions can test this method from their own
* packages.
*/
@VisibleForTesting
public void execute(String[] args, Runnable exitSuccessMethod, Runnable exitFailureMethod) {
Pair<String, Procedure<String[]>> commandEntry = getDeployCommand(args, exitFailureMethod);
LogUtil.FileLogger logAppender = LogUtil.getLogAppender(commandEntry.getOne());
StopWatch changeStopWatch = new StopWatch();
changeStopWatch.start();
LOG.info("Starting action at time [" + new Date() + "]");
boolean success = false;
Throwable processException = null;
try {
String[] argSubset = (String[]) ArrayUtils.subarray(args, 1, args.length);
commandEntry.getTwo().value(argSubset);
success = true;
} catch (Throwable t) {
processException = t;
} finally {
// We handle the exception and do system.exit in the finally block as we want a clean message to go out to users.
// If we just threw the runtime exception, then that would be the last thing that appears to users, which
// was confusing for users.
changeStopWatch.stop();
long runtimeSeconds = changeStopWatch.getTime() / 1000;
String successString = success ? "successfully" : "with errors";
LOG.info("");
LOG.info("Action completed {} at {}, took {} seconds.", successString, new Date(), runtimeSeconds);
LOG.info("");
if (processException != null) {
LOG.info("*** Exception stack trace ***", processException);
LOG.info("");
}
LOG.info("Detailed Log File is available at: {}", logAppender.getLogFile());
LOG.info("");
LOG.info("Exiting {}!", successString);
IOUtils.closeQuietly(logAppender);
if (processException != null) {
exitFailureMethod.run();
} else {
exitSuccessMethod.run();
}
}
}
示例13: logMethodTime
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
/**
* Around advice that logs methods times for all service methods.
*
* @param pjp the proceeding join point.
*
* @return the return value of the method we are advising.
* @throws Throwable if there were any problems executing the method.
*/
@Around("serviceMethods()")
public Object logMethodTime(ProceedingJoinPoint pjp) throws Throwable
{
// Get the target class being called.
Class<?> targetClass = pjp.getTarget().getClass();
// Get the target method being called.
MethodSignature targetMethodSignature = (MethodSignature) pjp.getSignature();
Method targetMethod = targetMethodSignature.getMethod();
if (targetMethod.getDeclaringClass().isInterface())
{
// Get the underlying implementation if we are given an interface.
targetMethod = pjp.getTarget().getClass().getMethod(pjp.getSignature().getName(), targetMethod.getParameterTypes());
}
// Only keep a stop watch if the class and method aren't suppressing logging and the log level is info.
if ((AnnotationUtils.findAnnotation(targetClass, SuppressLogging.class) == null) &&
(AnnotationUtils.findAnnotation(targetMethod, SuppressLogging.class) == null) && (LOGGER.isInfoEnabled()))
{
// Start the stop watch.
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// Proceed to the join point (i.e. call the method and let it return).
Object returnValue = pjp.proceed();
// Log the duration.
long durationMilliseconds = stopWatch.getTime();
LOGGER.info("javaMethod=\"{}.{}\" javaMethodDurationTimeInMilliseconds={} javaMethodDurationTimeFormatted=\"{}\"", targetClass.getName(),
targetMethodSignature.getName(), durationMilliseconds, HerdDateUtils.formatDuration(durationMilliseconds));
// Return the method return value.
return returnValue;
}
else
{
// Invoke the method normally.
return pjp.proceed();
}
}
示例14: iterator
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
@Override
public Iterator<FlexDocument> iterator() {
final StopWatch timer = new StopWatch();
Set<OWLObject> blacklist = new HashSet<>();
blacklist.add(graph.getDataFactory().getOWLThing());
blacklist.add(graph.getDataFactory().getOWLNothing());
Set<OWLObject> allOWLObjects =
graph.getAllOWLObjects().stream().filter(x -> !blacklist.contains(x)).collect(Collectors.toSet());
final int totalCount = allOWLObjects.size();
timer.start();
final Iterator<OWLObject> objectIterator = allOWLObjects.iterator();
return new Iterator<FlexDocument>() {
int counter = 0;
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public FlexDocument next() {
OWLObject obj = objectIterator.next();
FlexDocument doc = wring(obj, config);
counter++;
if( counter % 1000 == 0 ){
long elapsed = timer.getTime();
long eta = ((long)totalCount-counter) * (elapsed/((long)counter));
LOG.info("Loaded: " + Integer.toString(counter) + " of " + Integer.toString(totalCount)
+ ", elapsed: "+DurationFormatUtils.formatDurationHMS((elapsed))
+ ", eta: "+DurationFormatUtils.formatDurationHMS(eta));
}
return doc;
}
@Override
public boolean hasNext() {
return objectIterator.hasNext();
}
};
}
示例15: pauseTimer
import org.apache.commons.lang3.time.StopWatch; //导入方法依赖的package包/类
/**
* Pauses named timer (stopping measurement), can be resumed later.
* @param name name of timer to pause.
* @return time in milliseconds since timer was started.
*/
public long pauseTimer(String name) {
StopWatch sw = getStopWatch(name);
sw.suspend();
return sw.getTime();
}