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
Related
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.
This is my homework problem:
I have to do matrix multiplication. My code should create a thread to each element in the resultant matrix. i.e., if resultant matrix is mXn size then there should be m*n threads.
(http://iit.qau.edu.pk/books/OS_8th_Edition.pdf page 179)
Yes I finished it by my own. Which is executing fine with all my test cases. Unfortunately, I end up getting 70% credit :(
This is my code and test cases.
Matrix Multiplication.zip
When I met my professor regarding my marks. He told me that my code taking too long to execute larger size matrix.
I argued with him that it is a expected behavior as it is obvious that large size data takes more time. However, he disagree with me.
I attached my code and test cases . My code is taking 3 hours. As per my professor it should only take 5 min to execute.
I tried to figured out for last couple of days but I couldn't find exact solution :(
outline of my code
ExecutorService executor = Executors
.newFixedThreadPool(threadCount); // creating thread pool
// with fixed threads
int mRRowLen = matrix1.length; // m result rows length
int mRColLen = matrix2[0].length; // m result columns length
mResult = new long[mRRowLen][mRColLen];
for (int i = 0; i < mRRowLen; i++) { // rows from m1
for (int j = 0; j < mRColLen; j++) { // columns from m2
Runnable r = new MatrixMultipliactionThread(matrix1ColLen, i, j, matrix1,
matrix2);
executor.execute(r);
}
}
executor.shutdown();
while (!executor.isTerminated()) {
// wait untill it get shutdown
}
Run method :
public void run() {
for (int k = 0; k < m1ColLength; k++) { // columns from m1
Matrix.mResult[i][j] += matrix1[i][k] * matrix2[k][j];
}
Thanks in Advance
Ok, I downloaded your zip and ran the program. Your problem isn't in the matrix multiplication at all. The advice in the comments is still valid about reducing the number of threads, however as it stands the multiplication happens very quickly.
The actual problem is in your writeToAFile method - all the single-threaded CPU utilization you are seeing is actually happening in there, after the multiplication is already complete.
The way you're appending your strings:
fileOutputString = fileOutputString + resultMatrix[i][j]
creates thousands of new String objects which then immediately become garbage; this is very inefficient. You should be using a StringBuilder instead, something like this:
StringBuilder sb=new StringBuilder();
for (int i = 0; i < resultMatrix.length; i++) {
for (int j = 0; j < resultMatrix[i].length; j++) {
sb.append(resultMatrix[i][j]);
if (j != resultMatrix[i].length - 1) sb.append(",");
}
sb.append("\n");
}
String fileOutputString=sb.toString();
That code executes in a fraction of a second.
I'm programming a forcefield mod for Minecraft(a game.)
Here is my code so far:
if (Camb.killaura)
{
for(final int i= 0; i < mc.theWorld.loadedEntityList.size(); i++){
if((Entity)mc.theWorld.loadedEntityList.get(i) != this && getDistanceSqToEntity((Entity)mc.theWorld.loadedEntityList.get(i)) < 19.5D){
if(((Entity)mc.theWorld.loadedEntityList.get(i) instanceof EntityPlayer)){
mc.playerController.attackEntity(this, (Entity)mc.theWorld.loadedEntityList.get(i));
swingItem();
}
}
Everything works, but the issue is most servers only allow you to attack an entity 8 times a second. So my question is, how can I execute the following every .125 seconds? I asked a few fellow modders and they say they use nanoseconds, how can I do this?
This is the only code that needs the delay:
mc.playerController.attackEntity(this, (Entity)mc.theWorld.loadedEntityList.get(i));
swingItem();
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;
}
}
I make a benchmark like this :
for (int i = 0; i < 1000 * 1000; ++i) {
long var = System.nanoTime();
}
it takes 41 ms in my computer with jdk6.0
the follow code only costs 1 ms!!!
for (int i = 0; i < 1000 * 1000; ++i) {
System.nanoTime();
}
I think may be that time is costed by long var , so I make a test like this :
for (int i = 0; i < 1000 * 1000; ++i) {
long var = i;
}
it only costs 1 ms!!!
So,Why the first code block is so slow?
I'm a Chinese. Sorry for my poor English!
It really depends on how you run your benchmark. You most likely get <1ms runs because the JVM is not really running your code: it has determined that the code is not used and skips it:
for (int i = 0; i < 1000 * 1000; ++i) {
long var = i;
}
is equivalent to
//for (int i = 0; i < 1000 * 1000; ++i) {
// long var = i;
//}
and the JVM is probably running the second version.
You should read how to write a micro benchmark in Java or use a benchmarking library such as caliper.
It takes time for the JIT to detect your code doesn't do anything useful. The more complicated the code, the longer it takes (or it might not detect it at all)
In the second and third cases, it can replace the code with nothing (I suspect you can make it 100x longer and it won't run any longer)
Another possibility is you are running all three tests in the same method. When the first loop iterates more than 10,000 times, the whole method is compiled in the background such that when the second and third loops run they have been removed.
A simple way to test this is to change the order of the loops or better to place each loop in its own method to stop this.