I am making a game in Java and wanted to implement a deltatime system. However I am not sure if I have implemented it correctly. Is the way I have done it correct, or should I change it.
My code looks like this:
long oldtime = System.nanoTime();
while (true) {
long newtime = System.nanoTime();
long deltatime = (newtime - oldtime) / 1000000;
System.out.println(deltatime);
oldtime = newtime;
// render code
try {
Thread.sleep(Math.max(0, 32 - deltatime));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
It looks like you want to measure how long the rendering took. Therefore, I suggest a cleaner approach by storing the starting time in a variable (start) and then calculating the difference to the current time after the rendering took place. This would allow you to measure sub-steps easily by just adding another comparison to the current time in between.
Always be careful with the units (ms, µs, ms) and make it obvious by naming the variable accordingly (e.g. deltaMs) or by using a comment. It's also a good idea to protect the reference by declaring it final.
Here is a simple example:
while (true) {
final long start = System.nanoTime(); // initial reference
// simulate render code
try { Thread.sleep(32); } catch (InterruptedException e) { e.printStackTrace(); }
final long deltaMs = (System.nanoTime() - start) / 1_000_000;
System.out.println("Render took " + deltaMs + "ms");
}
Here is a nested example:
while (true) {
final long start = System.nanoTime();
/* A */ try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); }
final long deltaMsPartA = (System.nanoTime() - start) / 1_000_000;
System.out.println("Render part A took " + deltaMsPartA + "ms");
final long startPartB = System.nanoTime();
/* B */ try { Thread.sleep(30); } catch (InterruptedException e) { e.printStackTrace(); }
final long deltaMsPartB = (System.nanoTime() - startPartB) / 1_000_000;
System.out.println("Render part B took " + deltaMsPartB + "ms");
final long deltaMs = (System.nanoTime() - start) / 1_000_000;
System.out.println("Overall render took " + deltaMs + "ms");
}
Related
Getting exception when I assign large String value to Rserve in Java
public void run(String data) {//800
RConnection c =null;
long startTime = System.nanoTime();
ObjectMapper mapper = new ObjectMapper();
try {
c = new RConnection();
if (c.isConnected()) {
System.out.println("*** R serve is connected..");
} else {
System.err.println("R serve is not available");
}
System.out.println("data set length-->"+data.length());
c.assign("poleData",data);//This line is throwing error
c.eval(String.format("source(" + rScript + ")"));
REXP result =c.eval("imputResult");
System.out.println("Completed.."+imputeData.toPrettyString());
long endTime = System.nanoTime();
//System.out.println("Time end -->"+endTime);
long duration = endTime - startTime;
// System.out.println("Total time diff in nanosecond-->"+(endTime-startTime));
double diff = (double) duration / 1000000000;
// System.out.println("Total time diff -->" + diff + " second");
// c.close();
} catch (RserveException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(c!=null) {
c.close();
System.out.println("Connection closed..");
}
}
}
}
Exception
*** R serve is connected..
data set length-->58784021
java.lang.ArrayIndexOutOfBoundsException: Index 8452396 out of bounds for length 8452396
at org.rosuda.REngine.Rserve.RConnection.assign(RConnection.java:254)
at com.app.ImputaionJson$Task.run(ImputaionJson.java:190)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Connection closed..
Please help on this..
We are using web sockets in our project and there is a requirement on to evaluate the speed of websocket. How to measure the time taken by websocket to respond
Given that I am new in Stack Overflow and I can't write comments, I will try to give you an answer with the info that you posted.
If you go to Google you will find many examples about "How to calculate elapsed" or "execute time in Java". The following examples were extracted from mkyong
Date().getTime():
long lStartTime = new Date().getTime();
//some tasks
long lEndTime = new Date().getTime();
long difference = lEndTime - lStartTime;
System.out.println("Elapsed milliseconds: " + difference);
System.currentTimeMillis()
long lStartTime = System.currentTimeMillis();
//some tasks
long lEndTime = System.currentTimeMillis();
long difference = lEndTime - lStartTime;
System.out.println("Elapsed milliseconds: " + difference);
System.nanoTime()
long lStartTime = System.nanoTime();
//some tasks
long lEndTime = System.nanoTime();
long difference = lEndTime - lStartTime;
System.out.println("Elapsed milliseconds: " + difference/1000000);
Full example
import java.util.Date;
public class TimeApp {
public static void main(String[] argv) {
long lStartTime = new Date().getTime(); // start time
createArray(); // some tasks to eat time
long lEndTime = new Date().getTime(); // end time
long difference = lEndTime - lStartTime; // check different
System.out.println("Elapsed milliseconds: " + difference);
}
public static void createArray() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String sArray[] = new String[1000000];
for (int i = 0; i < 1000000; i++)
sArray[i] = "Array " + i;
}
}
Hopefully this will help you!
I am new to Java.I have a function where I want the function to execute a multithreaded behaviour.The problem is that I will be making the jar without main method inside it.. Just wanted to know that can we have a multithreaded function in Java without a class having main method ??
I have the following code and I want this "myHandler" function to have multithreaded behaviour such that whenever this function gets called,different threads execute it...Can you please help me this code executing multithreaded behaviour?? Thank You
public String myHandler(KinesisEvent kinesisEvent,Context context)
{
int singleRecord=0;
long starttime=System.currentTimeMillis();
//LambdaLogger lambdaLogger=context.getLogger();
for(KinesisEventRecord rec : kinesisEvent.getRecords())
{
singleRecord=0;
System.out.println("Kinesis Record inside is:"+new String(rec.getKinesis().getData().array()));
//count++;
singleRecord++;
// System.out.println(new String(rec.getKinesis().getData().array()));
}
count=count+singleRecord;
long endtime=System.currentTimeMillis();
long totaltime = endtime-starttime;
time=time+totaltime;
System.out.println("Time required to execute single Lambda function for "+singleRecord+" records is"+" :: "+totaltime+" milliseconds");
System.out.println("Total time required to execute Lambda function for "+count+" records is"+" :: "+time+" milliseconds");
return null;
}
I'm not sure if that is exactly what you want but you could do something like this:
public String myHandler(final KinesisEvent kinesisEvent, final Context context)
{
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
int singleRecord=0;
long starttime=System.currentTimeMillis();
//LambdaLogger lambdaLogger=context.getLogger();
for(KinesisEventRecord rec : kinesisEvent.getRecords())
{
singleRecord=0;
System.out.println("Kinesis Record inside is:"+new String(rec.getKinesis().getData().array()));
//count++;
singleRecord++;
// System.out.println(new String(rec.getKinesis().getData().array()));
}
count=count+singleRecord;
long endtime=System.currentTimeMillis();
long totaltime = endtime-starttime;
time=time+totaltime;
System.out.println("Time required to execute single Lambda function for "+singleRecord+" records is"+" :: "+totaltime+" milliseconds");
System.out.println("Total time required to execute Lambda function for "+count+" records is"+" :: "+time+" milliseconds");
}
});
thread.start();
}
This code will start your code in a new thread once you call the method but any parameters you want to use in the thread have to be declared final to be visible in the anonymous implementation of Runnable.
Another solution would be to create a new class and extend the Thread class:
public class MyHandlerThread extends Thread {
KinesisEvent kinesisEvent;
Context context;
public MyHandlerThread(KinesisEvent kinesisEvent, Context context) {
super();
this.kinesisEvent = kinesisEvent;
this.context = context;
}
#Override
public void run() {
int singleRecord = 0;
long starttime = System.currentTimeMillis();
//LambdaLogger lambdaLogger=context.getLogger();
for (KinesisEventRecord rec : kinesisEvent.getRecords()) {
singleRecord = 0;
System.out.println("Kinesis Record inside is:" + new String(rec.getKinesis().getData().array()));
//count++;
singleRecord++;
// System.out.println(new String(rec.getKinesis().getData().array()));
}
count = count + singleRecord;
long endtime = System.currentTimeMillis();
long totaltime = endtime - starttime;
time = time + totaltime;
System.out.println("Time required to execute single Lambda function for " + singleRecord + " records is" + " :: " + totaltime + " milliseconds");
System.out.println("Total time required to execute Lambda function for " + count + " records is" + " :: " + time + " milliseconds");
}
}
In order to start this as a thread you have to create an instance of the object and call its start method.
MyHandlerThread thread = new MyHandlerThread(param1, param2);
thread.start();
Hope this helps (:
If method should always be executed in separate thread, you can create a Thread, and call your code from that thread by following way:
public String myHandler(final KinesisEvent kinesisEvent, final Context context) {
new Thread(new Runnable() {
public void run() {
int singleRecord = 0;
long starttime = System.currentTimeMillis();
//LambdaLogger lambdaLogger=context.getLogger();
for (KinesisEventRecord rec : kinesisEvent.getRecords()) {
singleRecord = 0;
System.out.println("Kinesis Record inside is:" + new String(rec.getKinesis().getData().array()));
//count++;
singleRecord++;
// System.out.println(new String(rec.getKinesis().getData().array()));
}
count = count + singleRecord;
long endtime = System.currentTimeMillis();
long totaltime = endtime - starttime;
time = time + totaltime;
System.out.println("Time required to execute single Lambda function for " + singleRecord + " records is" + " :: " + totaltime + " milliseconds");
System.out.println("Total time required to execute Lambda function for " + count + " records is" + " :: " + time + " milliseconds");
return null;
}
}).start();
}
I want to hold down a key for a certain amount of time using the Java robot. I have read other similar threads, but none of them work. Repeatedly pressing the key will only result in the key not releasing.
Here's my code so far (It does not work since it only presses the key once):
new Thread(new Runnable() {
public void run() {
final int keyP = 0; //the key to press
final int duration = 2000 //2 seconds
Robot r = null;
try {
r = new Robot();
} catch (AWTException e1) {
e1.printStackTrace();
}
r.keyPress(keyP);
r.delay(duration); //Thread.sleep does the same thing
r.keyRelease(keyP);
}
}).start();
Try:
boolean keepPressing=true;
long startTime = System.currentTimeMillis();
long endTime=null;
long totalTime=null;
while(keepPressing){
r.keyPress(keyP);
endTime=System.currentTimeMillis();
totalTime = endTime - startTime;
if(totalTime>1999) {
keepPressing=false;
r.keyRelease(keyP);
}
}
I am developing an exam software in core java where I am conducting various tests for students.I am stuck at a piece of code where timer with countdown is set.
My problem is when I display minutes its working fine but when I try to display seconds with the minutes in mm:ss format its not working.
Code is:
// for below int ti=20,si=60;
// test is for 20 minutes
public void run() {
while (true) {
try {
Thread.currentThread().sleep(60000);
for (int i = 0; i <= 60; i++) {
etime.setText("Remaining Time:-" + ti + ":" + si);
System.out.println("Remaining Time:-" + ti + ":" + si);
Thread.currentThread().sleep(1000);
si--;
}
ti--;
if (ti == 0) {
close();
}
} catch (InterruptedException ex) {
Logger.getLogger(Exam.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Once si has counted down to 0, you need to reset it to 59.
Also, the i variable is completely unnecessary, and there is an off-by-one error in your loop.