Java - System.currentTimeMillis(); Not Returning Difference - java

For some reason I am getting a consistent 3600 returned by the function:
private static long getCountdownLeft() {
long now = System.currentTimeMillis();
long elapsedMillis = now - initialTime; //difference of current 'current' time
long millisLeft = secondsOfGame * 1000 - elapsedMillis;
return millisLeft/1000;
}
public static void Main(String[] args ) {
System.out.println("Time is " + getCountdownLeft());
}
private static int secondsOfGame = 3600;
private static long initialTime = System.currentTimeMillis();
This is event driven. I expect to see a difference in time everytime I invoke the function. I just use main to show that I am invoking it.

This is most probably because the elapsedMillis is coming as zero. I would suggest using System.nanoTime() for calculating elapsed time.
I'm not so sure how your code works (as is posted right now), but something like this might work. Note that you need to add your logic for computation, this is just a sample:
public class TimeTest {
private long startTime;
public TimeTest(){
startTime = System.nanoTime();
}
public void computeTimeDifference(){
long currentTime = System.nanoTime();
long elapsedTime = currentTime - startTime;
System.out.println("Difference: "+elapsedTime+ "ns");
}
public static void main(String[] args) {
new TimeTest().computeTimeDifference();
}
}

Your code will consume little time before invoke getCountdownLeft. try update this code :
public static void Main(String[] args) throws InterruptedException {
long gameTime = System.currentTimeMillis(); // pass the current time
Thread.currentThread().sleep(1000); // sleep one second before invoke getCountdownLeft
System.out.println("Time is " + getCountdownLeft(gameTime));
}

Hey I have just added print statements for prev, new and elapsed variables. The values are
previous time 1343882409054
present time 1343882409054
elapsed time 0
Time is 3600
So your millisLeft will always be 3600 .
But if you try using
System.nanoTime()
the values are,
previous time 519222175869357
present time 519222175923421
elapsed time 54064
Time is 3545
So you have to be more granular here and consider using System.nanoTime().

Related

How to calculate how many start-end pairs run in a given range of time-of-day

I have class called Running with start time and end time:
public class Running {
private double startTime;
private double endTime;
public Running(double startTime, double endTime) {
this.startTime = startTime;
this.endTime = endTime;
}
}
And in my main class:
Running runningA = new Running(1, 10);
Running runningB = new Running(5,9);
Running runningC = new Running(4, 8);
How can I calculate in the right way between which time most of them are running?
For example:
between 5 to 8 all of them are running
between 1 to 3 only one run
I'm not sure why the Running class holds the start time and end time as doubles rather than ints, but okay.
Using your example:
Running runningA = new Running(1, 10);
Running runningB = new Running(5, 9);
Running runningC = new Running(4, 8);
We create a List<Running> to hold the 3 instances of Running. Then we do the following:
Create a Map<Integer, Integer>
Go through the List<Running> and find the minimum start time and the maximum end time.
Start a time counter at the minimum start time.
Go through the List<Running> and see which instances have a time counter in their range. The first instance has a 1, for example. So we put a (time counter, 1) in the map.
Increment the time counter and repeat step 4 until the maximum end time.
The Map contains the answer for each time. Iterate through the Map and summarize which time periods have 1 instance, which time periods have 2 instances, and so on.
You can create a method in your class called 'isBetween' that returns if the object is between passed startTime and endTime:
public class Running {
private double startTime;
private double endTime;
public Running(double startTime, double endTime) {
this.startTime = startTime;
this.endTime = endTime;
}
public boolean isBetween(int startTime, int endTime) {
return return startTime>=this.startTime && endTime<=this.endTime && startTime<=endTime;
}
#Override
public String toString() {
return "Start time: " + this.startTime + " End time: " + this.endTime ;
}
}
And in your main method, you can verify if only one object is between two times, or if all objects in a list are between two given numbers:
public static void main(String[] args) {
Running runningA = new Running(1, 10);
Running runningB = new Running(5,9);
Running runningC = new Running(4, 8);
List<Running> list = new ArrayList<>();
list.add(runningA);
list.add(runningB);
list.add(runningC);
// for only one object:
System.out.println(runningA.isBetween(5, 8)); //print true if object is between 5 and 8
// for all objects in a list:
list.stream().filter(n -> n.isBetween(5, 8)).forEach(System.out::println); //print all objects between 5 and 8
}

How do i change NetBeans build time from seconds to milliseconds or nanoseconds?

Title says it all. I need to compare 2 small classes that are similar in ram usage and size and they have the same build time in seconds, but i need that time in milliseconds (no "convert from seconds to milliseconds formula", i need to know how many exact milliseconds passed).
I don't know is there any option for that.
You can use the below code to find build time by adding few lines into the main() method.
public static void main(String[] args) {
final long START = System.nanoTime();
//YOUR CODE HERE...
final long END = System.nanoTime();
System.out.println("Time taken : " + ((END - START) / 1e+9) + " seconds");
}
Time taken : 0.05408 seconds
I hope it might help someone :)
I use: System.currentTimeMillis(); Here's an example just to clear things
public static void main(String[] args) {
long startTime = System.currentTimeMillis(); //Store starting time
/*
CODE HERE
*/
System.out.println("Time taken : " + ( System.currentTimeMillis() - startTime ) + " millisecond(s)." );
}

The execution phase run for 2 minutes during which time customers will arrive randomly between 2 - 6 seconds and be placed into a queue

I managed to get the customers showing up at random times, the only problem I have now is wrapping the whole thing in a 2-minute timer without conflicting with the customer arrivals.
static Timer timer = new Timer();
static class Task extends TimerTask {
#Override
public void run() {
int delay = (new Random().nextInt(5)+2) * 1000;
timer.schedule(new Task(), delay);
System.out.println("Hi " + delay);
}
}
public static void main(String args[]) {
new Task().run();
}
This is what I have that works so far. I've tried wrapping it in another TimerTask, and using System.nanoTime() and a while loop. They both just end up conflicting with the customer arrivals. I usually like to figure things out on my own, but I've been working on this one part for hours and I can't figure it out.
Why not to use a sleep with a do-while loop like:
long durationMillis = TimeUnit.MINUTES.toMillis(2);
long endTime = System.currentTimeMillis() + durationMillis;
do {
int delaySec = ThreadLocalRandom.current().nextInt(2, 7);
TimeUnit.SECONDS.sleep(delaySec);
System.out.println("Hi " + delaySec);
} while (System.currentTimeMillis() < endTime);
Change delaySec semantics if you don't need to wait for whole seconds or 6 second wait is not inclusive.

Measure execution time for a Java method [duplicate]

This question already has answers here:
How do I time a method's execution in Java?
(42 answers)
Closed 9 years ago.
How do I calculate the time taken for the execution of a method in Java?
To be more precise, I would use nanoTime() method rather than currentTimeMillis():
long startTime = System.nanoTime();
myCall();
long stopTime = System.nanoTime();
System.out.println(stopTime - startTime);
In Java 8 (output format is ISO-8601):
Instant start = Instant.now();
Thread.sleep(63553);
Instant end = Instant.now();
System.out.println(Duration.between(start, end)); // prints PT1M3.553S
Guava Stopwatch:
Stopwatch stopwatch = Stopwatch.createStarted();
myCall();
stopwatch.stop(); // optional
System.out.println("Time elapsed: "+ stopwatch.elapsed(TimeUnit.MILLISECONDS));
You can take timestamp snapshots before and after, then repeat the experiments several times to average to results. There are also profilers that can do this for you.
From "Java Platform Performance: Strategies and Tactics" book:
With System.currentTimeMillis()
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);
}
}
With a StopWatch class
You can use this StopWatch class, and call start() and stop before and after the method.
class TimeTest2 {
public static void main(String[] args) {
Stopwatch timer = new Stopwatch().start();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
timer.stop();
System.out.println(timer.getElapsedTime());
}
}
See here (archived).
NetBeans Profiler:
Application Performance Application
Performance profiles method-level CPU
performance (execution time). You can
choose to profile the entire
application or a part of the
application.
See here.
Check this: System.currentTimeMillis.
With this you can calculate the time of your method by doing:
long start = System.currentTimeMillis();
class.method();
long time = System.currentTimeMillis() - start;
In case you develop applications for Android you should try out the TimingLogger class.
Take a look at these articles describing the usage of the TimingLogger helper class:
Measuring performance in the Android SDK (27.09.2010)
Discovering the Android API - Part 1 (03.01.2017)
You might want to think about aspect-oriented programming. You don't want to litter your code with timings. You want to be able to turn them off and on declaratively.
If you use Spring, take a look at their MethodInterceptor class.
If you are currently writing the application, than the answer is to use System.currentTimeMillis or System.nanoTime serve the purpose as pointed by people above.
But if you have already written the code, and you don't want to change it its better to use Spring's method interceptors. So for instance your service is :
public class MyService {
public void doSomething() {
for (int i = 1; i < 10000; i++) {
System.out.println("i=" + i);
}
}
}
To avoid changing the service, you can write your own method interceptor:
public class ServiceMethodInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = methodInvocation.proceed();
long duration = System.currentTimeMillis() - startTime;
Method method = methodInvocation.getMethod();
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
System.out.println("Method '" + methodName + "' took " + duration + " milliseconds to run");
return null;
}
}
Also there are open source APIs available for Java, e.g. BTrace.
or Netbeans profiler as suggested above by #bakkal and #Saikikos.
Thanks.
As proposed nanoTime () is very precise on short time scales.
When this precision is required you need to take care about what you really measure.
Especially not to measure the nanotime call itself
long start1 = System.nanoTime();
// maybe add here a call to a return to remove call up time, too.
// Avoid optimization
long start2 = System.nanoTime();
myCall();
long stop = System.nanoTime();
long diff = stop - 2*start2 + start1;
System.out.println(diff + " ns");
By the way, you will measure different values for the same call due to
other load on your computer (background, network, mouse movement, interrupts, task switching, threads)
cache fillings (cold, warm)
jit compiling (no optimization, performance hit due to running the compiler, performance boost due to compiler (but sometimes code with jit is slower than without!))
Nanotime is in fact not even good for elapsed time because it drifts away signficantly more than currentTimeMillis. Furthermore nanotime tends to provide excessive precision at the expense of accuracy. It is therefore highly inconsistent,and needs refinement.
For any time measuring process,currentTimeMillis (though almost as bad), does better in terms of balancing accuracy and precision.

How to compute accurately the time it takes a Java program to write or read a file?

How to compute accurately the time it takes a Java program to write or read a number of bytes from/to a file ?
It is really important that the time is being measured accurately. (The time should be computed by the program itself).
The standard idiom is:
long startTime = System.nanoTime();
doSomething();
long elapsedTime = System.nanoTime() - startTime;
not tested, but something like:
long delta = System.nanoTime();
try {
// do your stuff
} finally {
delta = System.nanoTime() - delta;
}
There is a code sample here:
http://www.goldb.org/stopwatchjava.html
/*
Copyright (c) 2005, Corey Goldberg
StopWatch.java is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
*/
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;
}
//sample usage
public static void main(String[] args) {
StopWatch s = new StopWatch();
s.start();
//code you want to time goes here
s.stop();
System.out.println("elapsed time in milliseconds: " + s.getElapsedTime());
}
}
The way I would do that is just run it in a loop some number of times. Like if you run it 1000 times and clock it, that gives you milliseconds. Run it 1,000,000 times, and it gives you microseconds.
If you also want to find out why it's taking as long as it is, you can just pause it some number of times (like 10) while it's running, and that will tell you what it's doing and why.
The problem with the get System.xxx method is that the method itself needs a few milliseconds to compute. The usually "accepted" way of doing it is running the test a few tens of thousands of times and calculating an average of this.
Also, depending on your OS there is something called the time granularity (example for windows). This is the smallest amount of time your OS can compute. On some OS its a millisecond, on some others its a nanosecond. It might or might not be relevant in your case.

Categories

Resources