Infinite for loop - java

This code works fine:
public class Main {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long endTime = startTime + 60000;
long index = 0;
while (true) {
double x = Math.sqrt(index);
long now = System.currentTimeMillis();
if (now > endTime) {
break;
}
index++;
}
System.out.println(index + " loops in one minute.");
}
}
But then, I tried rewriting it into a for loop, and it gets stuck in an infinite loop.
public class Main {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long endTime = startTime + 60000;
int i = 0;
for (long now = 0; now < endTime; i++) {
Math.sqrt(i);
now = System.currentTimeMillis();
System.out.println("now" + now);
System.out.println("end" + endTime);
}
}
System.out.println(i+"calculations done in one minute");
}

Your second example is not an infinite loop, just wait 1 minute.
long endTime = startTime + 60000;
set the endTime to 60000 milliseconds in the future, that means 60 seconds, means 1 minute.
The standard output is just printing extremely fast.
Put a Thread.sleep(1000L) in the loop and you will see 61 statements being printed before it ends.
long endTime = 1378140843604L; // for example
for (long now = 0; now < endTime; i++) {
now = System.currentTimeMillis(); // will be 1378140783604, 1378140784604, 1378140785604 and so on
System.out.println("now" + now);
System.out.println("end" + endTime);
Thread.sleep(1000L);
}

This worked for me:
public class Main {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long endTime = startTime + 60000;
int i = 0;
for (long now = 0; now < endTime; i++) {
Math.sqrt(i);
now = System.currentTimeMillis();
System.out.println("now" + now);
System.out.println("end" + endTime);
}
System.out.println(i+"calculations done in one minute");
}
}
The only difference between mine an yours is where I put this: (yours is outside the main method)
System.out.println(i+"calculations done in one minute");
You should also be aware it take just microseconds to run through the loop so you're getting a huge output.

Related

Android Java handler.postDelayed() remainingTime returns wrong value

I want to be able to calculate remaining time of myHandler2.postDelayed(). I was using this answer but it returns wrong value. Here is my code where the startTime variable is:
public void attackOnChibi(ChibiCharacter cc, boolean able) {
runnable = () -> {
Log.i("a", "a");
};
if (able) {
startTime = System.nanoTime();
myHandler2.postDelayed(runnable, count += 2000);
}
if (!able) {
myHandler2.removeCallbacksAndMessages(null);
count = 0;
}
}
And the code when I calculates and displays this remaining time:
elapsedTime = System.nanoTime() - gs.enemies.get(gs.enemyId - 1).startTime;
remainingTime = gs.enemies.get(gs.enemyId - 1).count + 2000 - TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS);
Log.i("elapsed/remaining", elapsedTime + " " + remainingTime);
Why it does not work? Help me please...

a method to get the runtime of another method

I know how to get the runtime of a method from here
How do I time a method's execution in Java?
Now I need to get the run time multiple times, so is there a way to make something like
public long exTime(methodToTime())
long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();
long duration = (endTime - startTime);
Thanks for your help
edit: to be more specific, my current code is
long startTime0 = System.nanoTime();
revealStr("1001*00*10");
long endTime0 = System.nanoTime();
long duration0 = (endTime0 - startTime0);
System.out.println("The runtime is " + endTime0);
System.out.println("10**01*1*0");
long startTime1 = System.nanoTime();
revealStr("10**01*1*0");
long endTime1 = System.nanoTime();
long duration1 = (endTime0 - startTime1);
System.out.println("The runtime is " + endTime1);
System.out.println("0*1*0**0**");
long startTime2 = System.nanoTime();
revealStr("0*1*0**0**");
long endTime2 = System.nanoTime();
long duration2 = (endTime2 - startTime2);
System.out.println("The runtime is " + endTime2);
System.out.println("****1*1***");
long startTime3 = System.nanoTime();
revealStr("****1*1***");
long endTime3 = System.nanoTime();
long duration3 = (endTime3 - startTime3);
System.out.println("The runtime is " + endTime3);
System.out.println("**********");
long startTime4 = System.nanoTime();
revealStr("**********");
long endTime4 = System.nanoTime();
long duration4 = (endTime4 - startTime4);
System.out.println("The runtime is " + endTime0);
which is repetitive and redundant
This is a util method I used to compare the performance of two method.
public static void testPerformance(long loopTime, Runnable r1,Runnable r2){
long startTime;
long endTime;
startTime=System.currentTimeMillis();
for (int i = 0; i < loopTime; i++) {
r1.run();
}
endTime=System.currentTimeMillis();
System.out.printf("loop %d times, total spend %d s, each spend %f ms\n",loopTime,(endTime-startTime)/1000,(double)(endTime-startTime)/loopTime);
startTime=System.currentTimeMillis();
for (int i = 0; i < loopTime; i++) {
r2.run();
}
endTime=System.currentTimeMillis();
System.out.printf("loop %d times, total spend %d s, each spend %f ms\n",loopTime,(endTime-startTime)/1000,(double)(endTime-startTime)/loopTime);
}
You can use like this:
PerformanceUtils.testPerformance(loopTime,()->{
//do some thing
},()->{
//do some thing
});

JAVA, got wrong value when using LongAdder in multi-thread

I am doing this exercise:
Generate 1,000 threads, each of which increments a counter
100,000 times. Compare the performance of using AtomicLong
versus LongAdder.
And the following is my implementation:
import java.io.*;
import java.util.*;
import java.nio.file.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class AtomicLongVsLongAddr {
// 9. Generate 1,000 threads, each of which increments a counter
// 100,000 times. Compare the performance of using AtomicLong
// versus LongAdder.
AtomicLong al = new AtomicLong(0);
LongAdder la = new LongAdder();
public class AtomicLongThread extends Thread {
#Override
public void run() {
for (int i = 0; i < 100000; i ++) {
al.incrementAndGet();
}
}
}
public class LongAdderThread extends Thread {
#Override
public void run() {
for (int i = 0; i < 100000; i ++) {
la.increment();
}
}
}
public static void main(String[] args) {
AtomicLongVsLongAddr vs = new AtomicLongVsLongAddr();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000; i ++) {
(vs.new AtomicLongThread()).start();
}
long endTime = System.currentTimeMillis();
System.out.printf("AtomicLong--Number: %s, Time: %d\n", vs.al, endTime - startTime);
startTime = System.currentTimeMillis();
for (int i = 0; i < 1000; i ++) {
(vs.new LongAdderThread()).start();
}
long res = vs.la.sum();
endTime = System.currentTimeMillis();
System.out.printf("LongAdder--Number: %s, Time: %d\n", res, endTime - startTime);
}
}
I got something like the following as the standard output every time I run this program:
AtomicLong--Number: 100000000, Time: 2330
LongAdder--Number: 99882179, Time: 469
Apparently I've got a wrong value with LongAdder, but I can not figure out where I did wrong.
Can you help me?
updated
Under the help of everybody here and #Ravindra Ranwala, I updated my answer for the exercise above:
import java.io.*;
import java.util.*;
import java.nio.file.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class AtomicLongVsLongAddr {
// 9. Generate 1,000 threads, each of which increments a counter
// 100,000 times. Compare the performance of using AtomicLong
// versus LongAdder.
AtomicLong al = new AtomicLong(0);
LongAdder la = new LongAdder();
public class AtomicLongThread extends Thread {
#Override
public void run() {
for (int i = 0; i < 100000; i ++) {
al.incrementAndGet();
}
}
}
public class LongAdderThread extends Thread {
#Override
public void run() {
for (int i = 0; i < 100000; i ++) {
la.increment();
}
}
}
public static void main(String[] args) {
try{
long startTime;
long endTime;
AtomicLongVsLongAddr vs = new AtomicLongVsLongAddr();
Thread[] t = new Thread[1000];
for (int i = 0; i < 1000; i ++) {
t[i] = vs.new AtomicLongThread();
}
startTime = System.currentTimeMillis();
for (int i = 0; i < 1000; i ++) {
t[i].start();
t[i].join();
}
endTime = System.currentTimeMillis();
System.out.printf("AtomicLong--Number: %s, Time: %d\n", vs.al, endTime - startTime);
for (int i = 0; i < 1000; i ++) {
t[i] = vs.new LongAdderThread();
}
startTime = System.currentTimeMillis();
for (int i = 0; i < 1000; i ++) {
t[i].start();
t[i].join();
}
long res = vs.la.sum();
endTime = System.currentTimeMillis();
System.out.printf("LongAdder--Number: %s, Time: %d\n", res, endTime - startTime);
} catch (Exception e) {
e.printStackTrace();
}
}
}
If there still are any wrong, please point it out for me. Thanks everyone.
Call Thread.join on all the threads and wait till all of them are completed. It seems your main thread exits before other threads that increment the two variables completed. What you are getting here is some intermediary result.
Here's the code,
public static void main(String[] args) throws InterruptedException {
final List<Thread> adderThreads = new ArrayList<>();
final List<Thread> atomicThreads = new ArrayList<>();
AtomicLongVsLongAddr vs = new AtomicLongVsLongAddr();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
final AtomicLongThread atomicThread = vs.new AtomicLongThread();
atomicThreads.add(atomicThread);
atomicThread.start();
}
for (Thread thread : atomicThreads) {
thread.join();
}
long endTime = System.currentTimeMillis();
System.out.printf("AtomicLong--Number: %s, Time: %d\n", vs.al, endTime - startTime);
startTime = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
final LongAdderThread adderThread = vs.new LongAdderThread();
adderThreads.add(adderThread);
adderThread.start();
}
for (Thread thread : adderThreads) {
thread.join();
}
long res = vs.la.sum();
endTime = System.currentTimeMillis();
System.out.printf("LongAdder--Number: %s, Time: %d\n", res, endTime - startTime);
}
Your code isn't synchronous - The main thread will exit/proceed before it's finished with the counter threads, thus creating the difference.

Calculating elapsed time of method

I'm trying to record the elapsed time for my method in milliseconds. Could someone tell me what I'm doing wrong?
public static void main(String[] args)
{
double pi = computePi(10000);
System.out.println(pi);
System.out.println(startTime - endTime);
}
long startTime = System.currentTimeMillis();
public static double computePi(int count)
{
double pi = 0;
for(int i = 0; i < count; i++)
{
pi += Math.pow(-1,i)/(2*i+1);
long endTime = System.currentTimeMillis();
}
return pi * 4;
return startTime - endTime;
}
}
The computation should be just before and after the method call. It should be endTime-startTime.
public static void main(String[] args)
{
long startTime = System.currentTimeMillis();
double pi = computePi(10000);
long endTime = System.currentTimeMillis();
System.out.println(pi);
System.out.println(endTime- startTime);
}

How to calculate the execution time of a Loop for one iteration?

Below is My code:
public class FindTime {
HashSet<String> hashSet = new HashSet<>();
long m1() {
hashSet.add("hai");
hashSet.add("me");
hashSet.add("you ");
hashSet.add("I");
hashSet.add("Us");
Iterator it = hashSet.iterator();
long startTime = System.currentTimeMillis();
while (it.hasNext()) {
System.out.println(it.next());
}
return startTime;
}
public static void main(String[] args) {
FindTime ft = new FindTime();
long startTime = ft.m1();
System.out.println("startTime" + startTime);
long endTime = System.currentTimeMillis();
System.out.println("End time" + endTime);
System.out.println("d/W" + (endTime - startTime));
}
}
I don't know is that one is correct way or not.My requirement is
"I want to calculate time taken to Iterate a HashSet".
To be more precise use System.nanoTime()
public class FindTime {
HashSet<String> hashSet = new HashSet<>();
long m1()
{
hashSet.add("hai");
hashSet.add("me");
hashSet.add("you ");
hashSet.add("I");
hashSet.add("Us");
Iterator it = hashSet.iterator();
long startTime = System.nanoTime();
while (it.hasNext()) {
System.out.println(it.next());
}
return startTime;
}
public static void main(String[] args) {
FindTime ft = new FindTime();
long startTime = ft.m1();
long endTime = System.nanoTime(); //CALCULATE THE END TIME BEFORE PRINTING START TIME
//BECAUSE PRINT OPERATION WILL ALSO TAKE TIME THAT WILL BE ADDED TO DIFFERENCE
System.out.println("Start time in nano seconds" + startTime); //No need because you actually need difference
System.out.println("End time in nano seconds" + endTime);
System.out.println("Difference in Nano Seconds" + (endTime - startTime));
//long microsecondsTime = (end - start) / 1000; //If you need in microseconds
}
}
Your code is correct. You've calculated the time which taken for iterating and printing the output in console. Print may take more time than iteration.
You may have also returned the execution time by
return System.currentTimeMillis()- startTime;
See Also : Do not use System.out.println in server side code
As you telling you need time to take only for iterate not for insertion then you can use it like
long m1() {
hashSet.add("hai");
hashSet.add("me");
hashSet.add("you ");
hashSet.add("I");
hashSet.add("Us");
Iterator it = hashSet.iterator();
long startTime = System.nanoTime();
while (it.hasNext()) {
System.out.println(it.next());
}
long endTime = System.nanoTime();
System.out.println("time taken in nano seconds" + endTime-startTime);
return endTime-startTime;
}
reason is if you take time into your main function then it will also calculate the time for insertion.
Yes I am agree that it will not affect too much but we know that is not right thing to do.Even here I am printing so here also it will add the printing time that is not exactly correct.

Categories