Running numbers with an iterator (homework) - java

i have this assignment that i cannot solve.
This question has probably been asked multiple times but i failed to find it so forgive me if i am indeed repeating a simple question.
This is the assignment:
Create a class named Benchmark.
Write a method that counts from 1 to 8.000.000 by 1s. Every time the count reaches a multiple of 1.000.000 print that number on the screen. Use your watch to time how long the loop takes.
Alternatively, you can use the system clock to time the duration of your program. You can do this by using the static method currentTimeMillis in the class System. See the documentation of the JDK for a detailed explanation on using this method.
The program should produce an output like this:
0
1000000
2000000
3000000
4000000
5000000
6000000
7000000
8000000
I found out that i need to use an iterator in order to get this done.
But my teacher is not available right now and i can't seem to find out how to use this.
Again: sorry for the newbie question, if someone could help me out with this.. I'd be forever gratefull ;)
Thanks for reading and thanks in advance for any help given!

Just:
for (int i = 1; i <= 8000000; i++) {
if (i % 1000000 == 0) {
System.out.println(i);
}
}
If you also want to measure the time:
long start = System.currentTimeMillis();
long end;
for (int i = 1; i <= 8000000; i++) {
if (i % 1000000 == 0) {
end = System.currentTimeMillis();
System.out.println(i);
System.out.println((end-start));
start = end;
}
}

Related

Java calculations that takes X amount of time

This is just a hypothetical question, but could be a way to get around an issue I have been having.
Imagine you want to be able to time a calculation function based not on the answer, but on the time it takes to calculating. So instead of finding out what a + b is, you wish to continue perform some calculation while time < x seconds.
Look at this pseudo code:
public static void performCalculationsForTime(int seconds)
{
// Get start time
int millisStart = System.currentTimeMillis();
// Perform calculation to find the 1000th digit of PI
// Check if the given amount of seconds have passed since millisStart
// If number of seconds have not passed, redo the 1000th PI digit calculation
// At this point the time has passed, return the function.
}
Now I know that I am horrible, despicable person for using precious CPU cycles to simple get time to pass, but what I am wondering is:
A) Is this possible and would JVM start complaining about non-responsiveness?
B) If it is possible, what calculations would be best to try to perform?
Update - Answer:
Based on the answers and comments, the answer seems to be that "Yes, this is possible. But only if it is not done in Android main UI thread, because the user's GUI will be become unresponsive and will throw an ANR after 5 seconds."
A) Is this possible and would JVM start complaining about non-responsiveness?
It is possible, and if you run it in the background, neither JVM nor Dalvik will complain.
B) If it is possible, what calculations would be best to try to perform?
If the objective is to just run any calculation for x seconds, just keep adding 1 to a sum until the required time has reached. Off the top of my head, something like:
public static void performCalculationsForTime(int seconds)
{
// Get start time
int secondsStart = System.currentTimeMillis()/1000;
int requiredEndTime = millisStart + seconds;
float sum = 0;
while(secondsStart != requiredEndTime) {
sum = sum + 0.1;
secondsStart = System.currentTimeMillis()/1000;
}
}
You can and JVM won't complain if your code is not part of some complex system that actually tracks thread execution time.
long startTime = System.currentTimeMillis();
while(System.currentTimeMillis() - startTime < 100000) {
// do something
}
Or even a for loop that checks time only every 1000 cycles.
for (int i = 0; ;i++) {
if (i % 1000 == 0 && System.currentTimeMillis() - startTime < 100000)
break;
// do something
}
As for your second question, the answer is probably calculating some value that can always be improved upon, like your PI digits example.

How to run java program only for 1 second? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I need to calibrate the machines, so my goal is to run a java program approximately for 1 second. So I could use the same program on other machine to measure their run time and calibrate it to 1 second.
I know 1 second run time is too small, it depends on various factors. But I was wondering if you guys could have any ideas that you would like to share about the calibration.
I want to run a java program for approximately one second. I want compiler to perform certain standard operations on an array. I have tried using for an array to find even and odd numbers.
The program output is not that important. The run time just has to be approximately for 1 second. The problem is that since 1 second is too small number, it gives a fluctuating run time like 1.25 sometimes or 0.678 sometimes.
Is there any way to force compiler only for 1 second without giving a large value of error.
PS: I do not want to use Thread.sleep(1000).
Right now, this is the code I am using. As I said, I am not bothered about the output and the operations as such. I just need a run time as 1 second. Please help me if you have any ideas.
long[] array = new long[5000000];
int repeat = 10;
long t1 = System.currentTimeMillis();
for(int j = 0; j <=repeat; j++)
{
int even = 0, odd = 0;
for(int i=0; i<array.length; i++)
{
array[i] = i;
}
for(int i=0; i<array.length; i++)
{
if(array[i] % 2 == 0)
even++;
else
odd++;
}
}
long t2 = System.currentTimeMillis();
long t3 = t2 - t1;
System.out.println(t3*10e-4+ " sec");
Hi I would recommend you to do this.
while(!(System.currentTimeMillis() - t1 >= 1000))
{
... your program
}
System.exit(0);
And for the record with skills in algorythms if you really don't need to remember all these number dont use the array.
you could get the same functionality in this code
for(int j = 0; j <=repeat; j++)
{
int even = 0, odd = 0;
for(int i=0; i<array.length; i++)
{
if(i%2 == 0){
even++;
}else{
odd++;
}
}
}
you will see it will run faster because you are not doing so many operations ... and you completly cut off the for cycle to 5000000 10 times
I hope this helped you improve the time

Strange code timing behavior in Java

In the following code:
long startingTime = System.nanoTime();
int max = (int) Math.pow(2, 19);
for(int i = 0; i < max; ){
i++;
}
long timePass = System.nanoTime() - startingTime;
System.out.println("Time pass " + timePass / 1000000F);
I am trying to calculate how much time it take to perform simple actions on my machine.
All the calculations up to the power of 19 increase the time it takes to run this code, but when I went above 19(up to max int value 31) I was amazed to discover that it have no effect on the time it takes.
It always shows 5 milliseconds on my machine!!!
How can this be?
You have just witnessed HotSpot optimizing your entire loop to oblivion. It's smart. You need to do some real action inside the loop. I recommend introducing an int accumulator var and doing some bitwise operations on it, and finally printing the result to ensure it's needed after the loop.
On the HotSpot JVM, -XX:CompileThreshold=10000 by default. This means a loop which iterates 10K times can trigger the whole method to be optimised. In your case you are timing how long it take to detect and compile (in the background) your method.
use another System.nanoTime() in the loop. no one can optimize this.
for(int i = 0; i < max; ){
i++;
dummy+=System.nanoTime();
}
dont forget to do:
System.out.println(dummy);
after the loop. ensures non-optimization

Comparing methods speed performance using nanotime in Java

I would like to compare the speed performance (if there were any) from the two readDataMethod() as I illustrate below.
private void readDataMethod1(List<Integer> numbers) {
final long startTime = System.nanoTime();
for (int i = 0; i < numbers.size(); i++) {
numbers.get(i);
}
final long endTime = System.nanoTime();
System.out.println("method 1 : " + (endTime - startTime));
}
private void readDataMethod2(List<Integer> numbers) {
final long startTime = System.nanoTime();
int i = numbers.size();
while (i-- > 0) {
numbers.get(i);
}
final long endTime = System.nanoTime();
System.out.println("method 2 : " + (endTime - startTime));
}
Most of the time the result I get shows that method 2 has "lower" value.
Run readDataMethod1 readDataMethod2
1 636331 468876
2 638256 479269
3 637485 515455
4 716786 420756
Does this test prove that the readDataMethod2 is faster than the earlier one ?
Does this test prove that the readDataMethod2 is faster than the earlier one ?
You are on the right track in that you're measuring comparative performance, rather than making assumptions.
However, there are lots of potential issues to be aware of when writing micro-benchmarks in Java. I would recommend that you read
How do I write a correct micro-benchmark in Java?
In the first one, you are calling numbers.size() for each iteration.
Try storing it in a variable, and check again.
The reason because of which the second version runs faster is because you are calling numbers.size() on each iteration. Replacing it by storing in a number would make it almost the same as the first one.
Does this test prove that the readDataMethod2 is faster than the earlier one ?
As #aix says, you are on the right track. However, there are a couple of specific issues with your methodology:
It doesn't look like you are "warming up" the JVM. Therefore it is conceivable that your figures could be distorted by startup effects (JIT compilation) or that none of the code has been JIT compiled.
I'd also argue that your runs are doing too little work. A 500000 nanoseconds, is 0.0005 seconds, and that's not much work. The risk is that "other things" external to your application could be introducing noise into the measurements. I'd have more confidence in runs that take tens of seconds.

Comparing logically similar "for loops"

I came across simple java program with two for loops. The question was whether these for loops will take same time to execute or first will execute faster than second .
Below is programs :
public static void main(String[] args) {
Long t1 = System.currentTimeMillis();
for (int i = 999; i > 0; i--) {
System.out.println(i);
}
t1 = System.currentTimeMillis() - t1;
Long t2 = System.currentTimeMillis();
for (int j = 0; j < 999; j++) {
System.out.println(j);
}
t2 = System.currentTimeMillis() - t2;
System.out.println("for loop1 time : " + t1);
System.out.println("for loop2 time : " + t2);
}
After executing this I found that first for loop takes more time than second. But after swapping there location the result was same that is which ever for loop written first always takes more time than the other. I was quite surprised with result. Please anybody tell me how above program works.
The time taken by either loop will be dominated by I/O (i.e. printing to screen), which is highly variable. I don't think you can learn much from your example.
The first loop will allocate 1000 Strings in memory while the second loop, regardsless of working forwards or not, can use the already pre-allocated objects.
Although working with System.out.println, any allocation should be neglible in comparison.
Long (and other primitive wrappers) has cache (look here for LongCache class) for values -128...127. It is populated at first loop run.
i think, if you are going to do a real benchmark, you should run them in different threads and use a higher value (not just 1000), no IO (printing output during execution time), and not to run them sequentially, but one by one.
i have an experience executing the same code a few times may takes different execution time.
and in my opinion, both test won't be different.

Categories