(Java Game Modding)How to delay this with nano time? - java

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();

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.

MultiThreading with for loops in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Alright so i have been trying to run a for loop that runs 60 times. In this for loop i am using Thread.sleep(2000); to ping a server. I want to do this 10 times for this thread but for a separate loop through the for loop. In the mean time i want another 6 threads running doing 10 of their own so this hole process is sped up and completed in around 12 seconds.
for(int i = 0; i < 6; i++) {
//I am starting a new thread here.
}
#Override
public void run() {
//THIS is where i want a each thread to be doing 10 each to speed up the process.
for(int i = 0; i < 60; i++) {
//Pinging server.
Thread.sleep(2000L);
//Gets info from server here. That is why there is a 2 second delay.
}
}
I am sorry if this is hard to understand but i tried setting this out in the simplest way possible.
Thanks in advance.
If I get You right, You are not depending on the results, right? Here is a quick handdraft made out of the code:
Thread[] t = new Thread[6];
for(int i = 0; i < 6; i++) {
t[i] = new Thread() {
#Override
public void run() {
for(int i = 0; i < 60; i++) {
//Pinging server.
Thread.sleep(2000L);
//Gets info from server here. That is why there is a 2 second delay.
}
}
};
t[i].start();
}
Thread.sleep(longEnough);
This is the cheapest variant for kicking off threads, but beware, it is not professional! You should at least loop over the thread array to call join() on them in order to wait long enough instead of using a time constant.
If You want to do serious threading please consider using Java's ExecutorService (see http://www.vogella.com/tutorials/JavaConcurrency/article.html#threadpools) or ForkJoin of Java 7 (http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html)
In your initial for loop, instead of creating Threads, you should be creating Callable instances. Add these into a List, create an Executor, and pass the List to the Executor (FixedThreadPool for example). Then execute the Executor and they'll run in parallel. After all these hints, Ill leave the implementation to you since this looks sneakingly like a homework question.

Running numbers with an iterator (homework)

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;
}
}

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

why it's so different between "long var = System.nanoTime()" and "System.nanoTime()" on time used?

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.

Categories