My StopWatch has wrong nano and millis, but right seconds - java

I've implemented a stopwatch class for my own little library and tested it by executing the following snippet:
public class Main {
public static void main(String[] args) throws Exception {
StopWatch sw = new StopWatch();
sw.start();
Thread.sleep(3000);
sw.stop();
System.out.println(sw.getMilli());
System.out.println(sw.getDuration().getNano());
System.out.println(sw.getDuration().getSeconds());
}
}
I get the following result:
20
2011600
3
You can see that the numbers differ. I checked my StopWatch class round about 10 times, but I cant find mistakes. Can you find them?
This is my stopwatch-implementation:
import java.time.Instant;
import java.time.Duration;
public class StopWatch {
private Instant startDate;
private Instant stopDate;
public StopWatch() {
reset();
}
public void start() {
if (startDate == null) {
startDate = Instant.now();
}
}
public void stop() {
if (stopDate == null && startDate != null) {
stopDate = Instant.now();
}
}
public void reset() {
startDate = null;
stopDate = null;
}
public Duration getDuration() {
if (startDate != null && stopDate != null) {
return Duration.between(startDate, stopDate);
}
return null;
}
public long getMilli() {
if (startDate != null && stopDate != null) {
return Duration.between(startDate, stopDate).getNano() / 1000000L;
}
return 0;
}
}

I missunderstood how objects of the class Duration work. getNano() does not return the total amount of nanoseconds between a range, but the rest of nanoseconds that do not fit into a whole second. I deleted getDuration() and reimplemented getMilli() like that:
public long getMilli() {
if (startDate != null && stopDate != null) {
Duration duration = Duration.between(startDate, stopDate);
long nanos = duration.getSeconds() * 1000000000 + duration.getNano();
return nanos / 1000000;
}
return 0;
}

Related

How to perform with longadder

Hello I have an application calculate time and throwing an event according that. I would like to make my application with thread safe using longadder or whatever is suitable.
my class below;
#Autowired
EventListenerConfiguration eventListenerConfiguration;
private volatile long lastReceivedMessage = System.currentTimeMillis();
public void consume(String message) Integer partition,
(Headers.OFFSET) Long offset, Acknowledgment ack) {
lastReceivedMessage = System.currentTimeMillis();
try {
seervice.processMessage(message, ack, null);
} catch (ParseException e) {
logger.error(e.getMessage());
}
}
#Scheduled(fixedDelayString = "${listenScheduled}", initialDelay = 100000)
private void distanceBetweenLastReceivedMessageAndCurrentTime() {
long currentTime = System.currentTimeMillis() - lastReceivedMessage;
if (currentTime >= EventListenerConfiguration .getTotalMilliSecondTimeForError()) {
EventUtil.publishEvent(THROW_ERROR_EVENT, EventSeverityStatus.ERROR, EventTypeStatus.CUSTOM, null);
} else (currentTime >= EventListenerConfiguration.getTotalMilliSecondTimeForWarn()) {
EventUtil.publishEvent(THROW_WARN_EVENT, EventSeverityStatus.WARN, EventTypeStatus.CUSTOM, null);
}
}
so basicly how to convert my code without changing much to longAdder and also perform currentTime-lastReceiveMessage
Thank you
Good Evening. It appears that your issue is largely that lastReceivedMessage is a protected resource used by two threads. Whatever is running the consume method generates it, and then the Spring-Generated #scheduled thread consumes it.
Adding the volatile keyword will not prevent the code from reading the field. It will only prevent the code from caching the variable. (Read up on volatile https://www.geeksforgeeks.org/volatile-keyword-in-java/) If you want to treat the #Scheduled block as a critical region, and prevent the updating of the lastRecievedMessage until it is complete, I would recommend the following:
private volatile long lastReceivedMessage = System.currentTimeMillis();
private Semaphore resourceLock = new Semaphore(1);
public void consume(String message) Integer partition,
(Headers.OFFSET) Long offset, Acknowledgment ack) {
resourceLock.acquireUninterruptibly();
try {
lastReceivedMessage = System.currentTimeMillis();
} finally {
resourceLock.release();
}
try {
seervice.processMessage(message, ack, null);
} catch (ParseException e) {
logger.error(e.getMessage());
}
}
#Scheduled(fixedDelayString = "${listenScheduled}", initialDelay = 100000)
private void distanceBetweenLastReceivedMessageAndCurrentTime() {
long currentTime = 0;
resourceLock.acquireUninterruptibly();
try {
currentTime = System.currentTimeMillis() - lastReceivedMessage;
if (currentTime >= EventListenerConfiguration .getTotalMilliSecondTimeForError()) {
EventUtil.publishEvent(THROW_ERROR_EVENT, EventSeverityStatus.ERROR, EventTypeStatus.CUSTOM, null);
} else (currentTime >= EventListenerConfiguration.getTotalMilliSecondTimeForWarn()) {
EventUtil.publishEvent(THROW_WARN_EVENT, EventSeverityStatus.WARN, EventTypeStatus.CUSTOM, null);
}
} finally {
resourceLock.release();
}
}

How to achieve parallelism and waiting for response that is used in subsequent steps in reactive programing

I am trying to replicate a scenario that we face in the production, which contains a mix of parallelism and waiting until some part is completed, dependent on the response.
Below is a replica of the code.
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static java.lang.Integer.sum;
public class Traditional {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Traditional traditional = new Traditional();
Instant start = Instant.now();
// traditional.executeMethod();
Instant end = Instant.now();
System.out.println("TimeTaken to execute sync :: " + Duration.between(start, end));
start = Instant.now();
traditional.executeMethodAsync();
end = Instant.now();
System.out.println("TimeTaken to execute async :: " + Duration.between(start, end));
start = Instant.now();
traditional.executeMethodReactive();
end = Instant.now();
System.out.println("TimeTaken to execute Reactively:: " + Duration.between(start, end));
}
private Integer executeMethodReactive() {
Scheduler scheduler = Schedulers.parallel();
Mono<Integer> a = Mono.just(firstMethod());
Mono<Integer> b = Mono.just(secondMethod());
Mono<Integer> c = Mono.just(thirdMethod());
Mono<Integer> externalMono = Mono.zip(a, b, c).subscribeOn(scheduler).flatMap(data -> {
Integer total = sum(data.getT1(), data.getT2());
Integer diff = diff(data.getT3(), data.getT1());
return Mono.zip(Mono.just(divide(total, diff)).subscribeOn(scheduler), Mono.just(multiply(total, diff)).subscribeOn(scheduler))
.flatMap(innerzip -> Mono.just(innerzip.getT1() + innerzip.getT2()));
});
Integer value = externalMono.block(Duration.ofMinutes(1));
System.out.println(value);
return value;
}
private int executeMethod() {
int a = firstMethod();
int b = secondMethod();
Integer c = thirdMethod();
Integer total = sum(a, b);
Integer diff = diff(c, a);
Integer d = divide(total, diff);
Integer multi = multiply(total, diff);
int value = d + multi;
System.out.println(value);
return value;
}
private Integer executeMethodAsync() throws ExecutionException, InterruptedException {
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(this::firstMethod);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(this::secondMethod);
CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(this::thirdMethod);
CompletableFuture.allOf(future1, future2, future3).join();
Integer total = sum(future1.get(), future2.get());
Integer diff = diff(future3.get(), future1.get());
CompletableFuture<Integer> future4 = CompletableFuture.supplyAsync(() -> divide(total, diff));
CompletableFuture<Integer> future5 = CompletableFuture.supplyAsync(() -> multiply(total, diff));
Function<Void, Integer> function = (voidValue) -> {
try {
return future4.get() + future5.get();
} catch (InterruptedException | ExecutionException e) {
return null;
}
};
CompletableFuture<Integer> finalTotal = CompletableFuture.allOf(future4, future5).thenApplyAsync(function);
System.out.println("Final Total :: " + finalTotal.get());
return finalTotal.get();
}
private int divide(Integer total, Integer diff) {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("divide");
return total / diff;
}
private int multiply(Integer total, Integer diff) {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("multiply");
return total * diff;
}
private Integer diff(Integer a, Integer b) {
return a - b;
}
private int firstMethod() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1");
return 1;
}
private int secondMethod() {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2");
return 2;
}
private int thirdMethod() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("3");
return 3;
}
}
sequential execution of the program is taking 18sec and Async execution is taking 11 sec, I am trying to achieve the same in reactive programming. How to achieve this?
Update
Based on the clue provided by martin, rewrote the method as below and it is working
private Integer executeMethodReactive() {
Scheduler scheduler = Schedulers.parallel();
Mono<Integer> externalMono = Mono.zip(Mono.fromCallable(this::firstMethod).log("first").subscribeOn(scheduler),
Mono.fromCallable(this::secondMethod).log("second").subscribeOn(scheduler),
Mono.fromCallable(this::thirdMethod).log("third").subscribeOn(scheduler)).flatMap(data -> {
Integer total = sum(data.getT1(), data.getT2());
Integer diff = diff(data.getT3(), data.getT1());
return Mono.zip(Mono.fromCallable(() -> divide(total, diff)).log("divide").subscribeOn(scheduler),
Mono.fromCallable(() -> multiply(total, diff)).log("multiply").subscribeOn(scheduler))
.flatMap(inner -> Mono.just(inner.getT1() + inner.getT2()));
});
return externalMono.block();
}

How to work with dynamic code in java method?

I have nearly redundant java methods. The body of these methods is always the same. Only one or two java expressions (java code lines) are different. I want to do a code refactoring of these nearly redundant methods, but I'm searching for the best way to do this. It's not so easy, because of the dynamic code lines.
Here are three methods with the same body but with dynmamic java code in it:
public static final boolean doSomething1() {
Date date = new Date();
long currentTime = date.getTime();
long maxTime = currentTime + (TIMEOUT * 1000);
while (currentTime < maxTime) {
try {
//START OF MY DYNAMIC CODE
//example 1
for (WebElement element : list) {
if (element.isDisplayed()) {
element.click();
return true;
}
}
//END OF MY DYNAMIC CODE
}
catch (Exception e) {
LOG.error("exception");
}
currentTime = new Date().getTime();
}
return false;
}
public static final boolean doSomething2() {
Date date = new Date();
long currentTime = date.getTime();
long maxTime = currentTime + (TIMEOUT * 1000);
while (currentTime < maxTime) {
try {
//START OF MY DYNAMIC CODE
//example 2
for (WebElement webElement : webElementList) {
WebElement parent = getParentElement(webElement);
}
return true;
//END OF MY DYNAMIC CODE
}
catch (Exception e) {
LOG.error("exception");
}
currentTime = new Date().getTime();
}
return false;
}
public static final boolean doSomething3() {
Date date = new Date();
long currentTime = date.getTime();
long maxTime = currentTime + (TIMEOUT * 1000);
while (currentTime < maxTime) {
try {
//START OF MY DYNAMIC CODE
//example 3
for (WebElement element : list) {
if (element.isDisplayed() && element.getText().equalsIgnoreCase(size))
return true;
}
//END OF MY DYNAMIC CODE
}
catch (Exception e) {
LOG.error("exception");
}
currentTime = new Date().getTime();
}
return false;
}
So, how is it possible to write one method with the opportunity to set the dynamic lines of code?
You could use the Strategy Pattern.
Example using BooleanSupplier as Strategy:
private static boolean doSomethingHelper(BooleanSupplier checker) {
Date date = new Date();
long currentTime = date.getTime();
long maxTime = currentTime + (TIMEOUT * 1000);
while (currentTime < maxTime) {
try {
if (checker.getAsBoolean())
return true;
}
catch (Exception e) {
LOG.error("exception");
}
currentTime = new Date().getTime();
}
return false;
}
public static boolean doSomething1() {
return doSomethingHelper(() -> true);
}
public static boolean doSomething2() {
return doSomethingHelper(() -> false);
}
public static boolean doSomething3() {
return doSomethingHelper(() -> {
System.out.println("test");
return true;
});
}
Pass a boolean parameter whose value is the first operand of the X == true (which is more easily written as X):
public static final boolean doSomething1() {
return doSomethingCommon(true);
}
public static final boolean doSomething2() {
return doSomethingCommon(false);
}
private static final boolean doSomethingCommon(boolean param) {
// ...
if (param) {
return true;
}
// ...
}
You have several choices:
Aspect oriented programming
Strategy design pattern
Lambdas in JDK 8.
I'd prefer that last one. Everyone should be using JDK 8 now.
I hope lines of code like this are just hastily written poor examples, not typical of the way you write:
if (true == true)
Use the Template Method design pattern:
abstract class DynamicImpl {
protected abstract boolean doSomethingImpl();
public final boolean doSomething() {
Date date = new Date();
long currentTime = date.getTime();
long maxTime = currentTime + (TIMEOUT * 1000);
while (currentTime < maxTime) {
try {
if (doSomethingImpl()) {
return true;
}
}
catch (Exception e) {
LOG.error("exception");
}
currentTime = new Date().getTime();
}
return false;
}
}
With this class in place you can do your static methods as follows:
private static final DynamicImpl d1 = new DynamicImpl() {
protected boolean doSomethingImpl() {
return true;
}
};
private static final DynamicImpl d2 = new DynamicImpl() {
protected boolean doSomethingImpl() {
return false;
}
};
private static final DynamicImpl d3 = new DynamicImpl() {
protected boolean doSomethingImpl() {
System.out.println("test")
return true;
}
};
public static final boolean doSomething1() {
return d1.doSomething();
}
public static final boolean doSomething2() {
return d2.doSomething();
}
public static final boolean doSomething3() {
return d3.doSomething();
}

Hystrix Circuit Breaker won't open?

I'm trying to learn how to use Hystrix. I've created this class below:
public class CommandReturnAllExceptFive extends HystrixCommand<Integer> {
public static final Integer SLEEP_TIME = 5000;
private Integer x;
public CommandReturnAllExceptFive(Integer x) {
super(getHystrixConfiguration());
this.x = x;
System.out.println("Is circuit breaker open? " + (this.circuitBreaker.isOpen() ? "yes" : "no"));
System.out.println("Requests so far: "+(this.metrics.getRollingCount(HystrixEventType.FAILURE)));
}
public void setX(Integer x) {
this.x = x;
}
private static HystrixCommand.Setter getHystrixConfiguration() {
HystrixCommandProperties.Setter properties
= HystrixCommandProperties.Setter()
.withCircuitBreakerSleepWindowInMilliseconds(SLEEP_TIME)
.withCircuitBreakerEnabled(true)
.withCircuitBreakerRequestVolumeThreshold(1)
.withCircuitBreakerErrorThresholdPercentage(1)
.withMetricsRollingStatisticalWindowBuckets(1)
.withMetricsRollingStatisticalWindowBuckets(1);
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ReturnAllExceptFive");
return HystrixCommand.Setter.withGroupKey(groupKey).andCommandPropertiesDefaults(properties);
}
protected Integer run() throws Exception {
if (x == 5) {
throw new Exception();
}
return x;
}
}
with the following unit test:
#Test
public void testCommandReturnAllExceptFive_doesStallBeforeCallingAgain() {
boolean exceptionIsThrown = false;
try {
CommandReturnAllExceptFive returnAllExceptFive = new CommandReturnAllExceptFive(5);
returnAllExceptFive.execute();
} catch (Exception ex) {
exceptionIsThrown = true;
}
assertThat(exceptionIsThrown, is(true));
long timeNow = System.currentTimeMillis();
boolean callIsSuccessful = false;
while (!callIsSuccessful) {
try {
CommandReturnAllExceptFive returnAllExceptFive = new CommandReturnAllExceptFive(1);
returnAllExceptFive.execute();
callIsSuccessful = true;
} catch (Exception ex) {
}
}
long timeAfter = System.currentTimeMillis();
long timeToSuccess = timeAfter - timeNow;
System.out.println("timeNow: "+timeNow+"\ntimeAfter: "+timeAfter);
//assertThat(timeToSuccess >= CommandReturnAllExceptFive.SLEEP_TIME, is(true));
}
which is basically verifying that the call fails at 5, and that it does stall for the specified period of time after a successful execution. The debugging statements indicate that the circuit is never closed, but it should be closed after the first call since that one throws an exception, hence indicating failure. Can anyone help me out here?

Is there a stopwatch in Java?

Is there a stopwatch in Java?
On Google I only found code of stopwatches that don't work - they always return 0 milliseconds.
This code I found doesn't work and I don't see why.
public class StopWatch {
private long startTime = 0;
private long stopTime = 0;
private boolean running = false;
public void start() {
this.startTime = System.currentTimeMillis();
this.running = true;
}
public void stop() {
this.stopTime = System.currentTimeMillis();
this.running = false;
}
//elaspsed time in milliseconds
public long getElapsedTime() {
long elapsed;
if (running) {
elapsed = (System.currentTimeMillis() - startTime);
} else {
elapsed = (stopTime - startTime);
}
return elapsed;
}
//elaspsed time in seconds
public long getElapsedTimeSecs() {
long elapsed;
if (running) {
elapsed = ((System.currentTimeMillis() - startTime) / 1000);
} else {
elapsed = ((stopTime - startTime) / 1000);
}
return elapsed;
}
}
You'll find one in
http://commons.apache.org/lang/
It's called
org.apache.commons.lang.time.StopWatch
But it roughly does the same as yours. If you're in for more precision, use
System.nanoTime()
See also this question here:
Time measuring overhead in Java
Use Guava's Stopwatch class.
An object that measures elapsed time in nanoseconds. It is useful to
measure elapsed time using this class instead of direct calls to
System.nanoTime() for a few reasons:
An alternate time source can be substituted, for testing or performance reasons.
As documented by nanoTime, the value returned has no absolute meaning, and can only be interpreted as relative to another timestamp
returned by nanoTime at a different time. Stopwatch is a more
effective abstraction because it exposes only these relative values,
not the absolute ones.
Stopwatch stopwatch = Stopwatch.createStarted();
doSomething();
stopwatch.stop(); // optional
long millis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
log.info("that took: " + stopwatch); // formatted string like "12.3 ms"
Now you can try something like:
Instant starts = Instant.now();
Thread.sleep(10);
Instant ends = Instant.now();
System.out.println(Duration.between(starts, ends));
Output is in ISO 8601.
Spring provides an elegant org.springframework.util.StopWatch class (spring-core module).
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// Do something
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeMillis());
There's no built in Stopwatch utility but as of JSR-310 (Java 8 Time) you can do this simply.
ZonedDateTime now = ZonedDateTime.now();
// Do stuff
long seconds = now.until(ZonedDateTime.now(), ChronoUnit.SECONDS);
I haven't benchmarked this properly but I would guess using Guava's Stopwatch is more effective.
The code doesn't work because elapsed variable in getElapsedTimeSecs() is not a float or double.
Use System.currentTimeMillis() to get the start time and the end time and calculate the difference.
class TimeTest1 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
}
}
More info at this tutorial
Try this:
/*
* calculates elapsed time in the form hrs:mins:secs
*/
public class StopWatch
{
private Date startTime;
public void startTiming()
{
startTime = new Date();
}
public String stopTiming()
{
Date stopTime = new Date();
long timediff = (stopTime.getTime() - startTime.getTime())/1000L;
return(DateUtils.formatElapsedTime(timediff));
}
}
Use:
StopWatch sw = new StopWatch();
...
sw.startTiming();
...
String interval = sw.stopTiming();
use : com.google.common.base.Stopwatch, its simple and easy.
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
example:
Stopwatch stopwatch = new Stopwatch();
stopwatch.start();
"Do something"
logger.debug("this task took " + stopwatch.stop().elapsedTime(TimeUnit.MILLISECONDS) + " mills");
this task took 112 mills
try this
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class millis extends JFrame implements ActionListener, Runnable
{
private long startTime;
private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss.SSS");
private final JButton startStopButton= new JButton("Start/stop");
private Thread updater;
private boolean isRunning= false;
private final Runnable displayUpdater= new Runnable()
{
public void run()
{
displayElapsedTime(System.currentTimeMillis() - millis.this.startTime);
}
};
public void actionPerformed(ActionEvent ae)
{
if(isRunning)
{
long elapsed= System.currentTimeMillis() - startTime;
isRunning= false;
try
{
updater.join();
// Wait for updater to finish
}
catch(InterruptedException ie) {}
displayElapsedTime(elapsed);
// Display the end-result
}
else
{
startTime= System.currentTimeMillis();
isRunning= true;
updater= new Thread(this);
updater.start();
}
}
private void displayElapsedTime(long elapsedTime)
{
startStopButton.setText(timerFormat.format(new java.util.Date(elapsedTime)));
}
public void run()
{
try
{
while(isRunning)
{
SwingUtilities.invokeAndWait(displayUpdater);
Thread.sleep(50);
}
}
catch(java.lang.reflect.InvocationTargetException ite)
{
ite.printStackTrace(System.err);
// Should never happen!
}
catch(InterruptedException ie) {}
// Ignore and return!
}
public millis()
{
startStopButton.addActionListener(this);
getContentPane().add(startStopButton);
setSize(100,50);
setVisible(true);
}
public static void main(String[] arg)
{
new Stopwatch().addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
millis s=new millis();
s.run();
}
}
try this http://introcs.cs.princeton.edu/java/stdlib/Stopwatch.java.html
that's very easy
Stopwatch st = new Stopwatch();
// Do smth. here
double time = st.elapsedTime(); // the result in millis
This class is a part of stdlib.jar
Simple out of the box Stopwatch class:
import java.time.Duration;
import java.time.Instant;
public class StopWatch {
Instant startTime, endTime;
Duration duration;
boolean isRunning = false;
public void start() {
if (isRunning) {
throw new RuntimeException("Stopwatch is already running.");
}
this.isRunning = true;
startTime = Instant.now();
}
public Duration stop() {
this.endTime = Instant.now();
if (!isRunning) {
throw new RuntimeException("Stopwatch has not been started yet");
}
isRunning = false;
Duration result = Duration.between(startTime, endTime);
if (this.duration == null) {
this.duration = result;
} else {
this.duration = duration.plus(result);
}
return this.getElapsedTime();
}
public Duration getElapsedTime() {
return this.duration;
}
public void reset() {
if (this.isRunning) {
this.stop();
}
this.duration = null;
}
}
Usage:
StopWatch sw = new StopWatch();
sw.start();
// doWork()
sw.stop();
System.out.println( sw.getElapsedTime().toMillis() + "ms");
Try this.
public class StopWatch {
private long startTime = 0;
private long stopTime = 0;
public StopWatch()
{
startTime = System.currentTimeMillis();
}
public void start() {
startTime = System.currentTimeMillis();
}
public void stop() {
stopTime = System.currentTimeMillis();
System.out.println("StopWatch: " + getElapsedTime() + " milliseconds.");
System.out.println("StopWatch: " + getElapsedTimeSecs() + " seconds.");
}
/**
* #param process_name
*/
public void stop(String process_name) {
stopTime = System.currentTimeMillis();
System.out.println(process_name + " StopWatch: " + getElapsedTime() + " milliseconds.");
System.out.println(process_name + " StopWatch: " + getElapsedTimeSecs() + " seconds.");
}
//elaspsed time in milliseconds
public long getElapsedTime() {
return stopTime - startTime;
}
//elaspsed time in seconds
public double getElapsedTimeSecs() {
double elapsed;
elapsed = ((double)(stopTime - startTime)) / 1000;
return elapsed;
}
}
Usage:
StopWatch watch = new StopWatch();
// do something
watch.stop();
Console:
StopWatch: 143 milliseconds.
StopWatch: 0.143 seconds.
Performetrics provides a convenient Stopwatch class, just the way you need. It can measure wall-clock time and more: it also measures CPU time (user time and system time) if you need.
It's small, free and you can download from Maven Central.
More information and examples can be found here: https://obvj.net/performetrics
Stopwatch sw = new Stopwatch();
sw.start();
// Your code
sw.stop();
sw.printStatistics(System.out);
// Sample output:
// +-----------------+----------------------+--------------+
// | Counter | Elapsed time | Time unit |
// +-----------------+----------------------+--------------+
// | Wall clock time | 85605718 | nanoseconds |
// | CPU time | 78000500 | nanoseconds |
// | User time | 62400400 | nanoseconds |
// | System time | 15600100 | nanoseconds |
// +-----------------+----------------------+--------------+
You can convert the metrics to any time unit (nanoseconds, milliseconds, seconds, etc...)
PS: I am the author of the tool.
You can find a convenient one here:
https://github.com/varra4u/utils4j/blob/master/src/main/java/com/varra/util/StopWatch.java
Usage:
final StopWatch timer = new StopWatch();
System.out.println("Timer: " + timer);
System.out.println("ElapsedTime: " + timer.getElapsedTime());
Try this.
Java Stopwatch Fully Working Solution
Here you will get a fully working solution.
Just a snippet from the above-linked solution:
You can create a class like below code and use this class' start and stop method before and after the code section, you want to measure the time taken.
public class Stopwatch{
private long startTime;
private long stopTime;
/**
starting the stop watch.
*/
public void start(){
startTime = System.nanoTime();
}
/**
stopping the stop watch.
*/
public void stop()
{ stopTime = System.nanoTime(); }
/**
elapsed time in nanoseconds.
*/
public long time(){
return (stopTime - startTime);
}
public String toString(){
return "elapsed time: " + time() + " nanoseconds.";
}
}
Thank you.
Try this...
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
public class StopwatchTest {
public static void main(String[] args) throws Exception {
Stopwatch stopwatch = Stopwatch.createStarted();
Thread.sleep(1000 * 60);
stopwatch.stop(); // optional
long millis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
System.out.println("Time in milliseconds "+millis);
System.out.println("that took: " + stopwatch);
}
}
I have created a Stopwatch that has everything you might need in it.
I even documented it!
And I also compiled it for faster usage.
Here's an example:
//...
//For demo only!
public static void main(String[]a){
final Stopwatch stopwatch=new Stopwatch();
stopwatch.start();
try{
java.lang.Thread.sleep(1000);
}catch(Exception e){}
stopwatch.split();
System.out.println("Time elapsed in nanoseconds: "+stopwatch.getTimeElapsed());
System.out.println("Time elapsed in milliseconds: "+stopwatch.getTimeElapsed(Stopwatch.millis));
System.out.println("Time elapsed in seconds: "+stopwatch.getTimeElapsed(Stopwatch.seconds));
try{
java.lang.Thread.sleep(1000);
}catch(Exception e){}
stopwatch.split();
final long[][] laps=stopwatch.getLaps();
for(long[] lap:laps){
System.out.println(java.util.Arrays.toString(lap));
}
}
//...
This is not for promotion, made this to help people not waste their time in coding classes themselves!

Categories