how to solve the problem in the log cat .. the error says wait time is negative and it crashes on imulator and external device
this is my code in java android activity
public void run() {
long startTime;
long timeMills;
long waitTime;
long totalTime = 0;
int frameCount = 0;
long targetTime = 1000/FPS;
while (running){
startTime = System.nanoTime();
canvas = null;
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder){
this.gamePanel.update();
this.gamePanel.draw(canvas);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(canvas != null){
try {
surfaceHolder.unlockCanvasAndPost(canvas);
}catch (Exception e){
e.printStackTrace();
}
}
}
timeMills = (System.nanoTime() - startTime) / 1000000;
waitTime = targetTime - timeMills;
try {
this.sleep(waitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
totalTime += System.nanoTime() - startTime;
frameCount++;
if(frameCount == FPS){
avrageFPS = 1000 / (totalTime/frameCount) / 1000;
frameCount = 0;
totalTime = 0;
System.out.print(avrageFPS);
}
}
}
and this is the log
java.lang.IllegalArgumentException: millis < 0: -136
Your code does this:
long targetTime = 1000/FPS;
while (...) {
startTime = System.nanoTime();
... do lots of work ...
timeMills = (System.nanoTime() - startTime) / 1000000;
waitTime = targetTime - timeMills;
If the time required to prepare and render a frame exceeds targetTime, then waitTime will be negative. The complexity of your animation, and the value for FPS, affect how likely this is to happen.
The easiest fix is simply:
if (waitTime < 0) { waitTime = 0; }
That way, if your rendering is taking too long and you're missing deadlines, you don't sleep at all.
A better fix would be to structure the game to run off the display's timing, rather than having a fixed notion of frame rate, and to drop frames when you fall behind. More information about this can be found in this appendix to the graphics architecture doc.
Related
I have a scheduled method with integer values with conditions and also have long values for checking these conditions, My code is working however I would like to make a thread safe for long values, I have found AtomicInteger but I do not know how to apply on my code;
My code below;
Yaml file;
listenForInfo: 20000
listenForWarn: 30000
listenForError: 40000
listenScheduled: 1000
My main code;
#Value("${listenForInfo}")
private int listenForInfo;
#Value("${listenForWarn}")
private int listenForWarn;
#Value("${listenForError}")
private int listenForError;
private long lastReceivedMessage = System.nanoTime();
#KafkaListener(topics = "#{'${kafka.topic}'}", groupId = "#{'${kafka.groupid}'}")
public void consume(String message, #Header(KafkaHeaders.RECEIVED_PARTITION_ID) Integer partition,
#Header(KafkaHeaders.OFFSET) Long offset, Acknowledgment ack) {
logger.info("offset = {} ", offset);
logger.info("partition = {} ", partition);
logger.info("kafka Message : {}", message);
lastReceivedMessage = System.nanoTime();
try {
service.processMessage(message, ack, null);
} catch (ParseException e) {
logger.error(e.getMessage());
}
}
#Scheduled(fixedDelayString = "${listenScheduled}", initialDelay = 1000)
private void distanceBetweenLastReceivedMessageAndCurrentTime() {
long currentTime = (System.nanoTime() - lastReceivedMessage) / 1000000;
logger.info("current time : {}", currentTime);
if (currentTime >= listenForInfo && currentTime < listenForWarn) {
EventUtil.publishEvent("event info ", EventSeverityStatus.INFO, EventTypeStatus.CUSTOM, null);
}
if (currentTime >= listenForWarn && currentTime < listenForError) {
EventUtil.publishEvent("event warn ", EventSeverityStatus.WARN, EventTypeStatus.CUSTOM, null);
}
if (currentTime >= listenForError) {
EventUtil.publishEvent("event error ", EventSeverityStatus.ERROR, EventTypeStatus.CUSTOM, null);
}
}
I am working with websockets, i want the process of sending/recieving data be as fast as possible. I have come across BSON and MsgPack libraries for binary serialization. However, using simple tests:
#Message
class MessageTemplate implements Serializable {
public String msg;
}
public class test {
static void start(){
MessageTemplate x = new MessageTemplate();
for (int i = 0; i < 1000; ++i)
x.msg += UUID.randomUUID().toString();
System.out.println("===============================================================");
{
long startTime = System.nanoTime();
byte[] bytes = SerializationUtils.serialize(x);
MessageTemplate x1 = (MessageTemplate) SerializationUtils.deserialize(bytes);
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("TIME1:" + String.valueOf(duration) + ", SIZE: " + bytes.length);
}
System.out.println("===============================================================");
MessagePack msgpack = new MessagePack();
{
long startTime = System.nanoTime();
try {
byte[] b = msgpack.write(x);
MessageTemplate dst = msgpack.read(b, MessageTemplate.class);
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("TIME1:" + String.valueOf(duration) + ", SIZE: " + b.length);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Output:
starting===============================================================
TIME1:2560388, SIZE: 36171
===============================================================
TIME1:93729732, SIZE: 36013
It seems that serialization is way faster than MsgPack. However searching i have found not any mentioning of java serialization as "serializating library/format".
What are the drawbacks of using it? Why is it or isnt used? The only drawback i see is that mobile app will have ios/android client, so there wont be java on both sides in every case.
Thanks for help and answers.
I need to display lots of files with filename and icon in my program.
Therefor I am extracting the icons from the files, but it takes too long.
I have tried 2 different methods to extract the icons, but both are really slow (in my case REALLY slow, because I get the files from a networkdrive).
Here is an example, where I extract the icons and count the number of icons (do nothing with the files/icons)
public class Main {
public static void main(String[] args) {
File folder = new File("C:\\Windows\\System32\\");
File[] list = folder.listFiles();
for(int i = 0; i< 3; i++) {
long startTime = System.currentTimeMillis();
System.out.println("Method 1: " + getIconNumber1(list)+ " Icons");
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("Finished Method 1 in " + (float) elapsedTime / 1000 + "sec");
long startTime2 = System.currentTimeMillis();
System.out.println("Method 2: " + getIconNumber2(list)+ " Icons");
long stopTime2 = System.currentTimeMillis();
long elapsedTime2 = stopTime2 - startTime2;
System.out.println("Finished Method 2 in " + (float) elapsedTime2 / 1000 + "sec");
System.out.println("-----------------");
}
}
private static int getIconNumber1(File[] list) {
int nr = 0;
for(File f : list) {
try {
ShellFolder sf = ShellFolder.getShellFolder(f);
ImageIcon icon = new ImageIcon(sf.getIcon(true));
nr++;
} catch (Exception e) {
e.printStackTrace();
}
}
return nr;
}
private static int getIconNumber2(File[] list) {
int nr = 0;
for(File f : list){
FileSystemView view = FileSystemView.getFileSystemView();
Icon icon = view.getSystemIcon(f);
nr++;
}
return nr;
}
}
Is there a faster way to do this?
May I know How to insert a stop watch for this piece of code from Poll() method...I have to make start count such that before the database starts and amount of time it took for polling.
public void poll() throws Exception {
st = conn.createStatement();
for (int i=0; i<10; i++)
{
Timestamp start;
rs = st.executeQuery( "select * from msg_new_to_bde" );
Timestamp end;
//speed = end - start;
Collection<KpiMessage> pojoCol = new ArrayList<KpiMessage>();
while (rs.next()) {
KpiMessage filedClass = convertRecordsetToPojo(rs);
pojoCol.add(filedClass);
}
for (KpiMessage pojoClass : pojoCol) {
System.out.println("=== Iteratioin Nr. " + i + "====");
System.out.print(pojoClass.getSequence());
System.out.print(pojoClass.getTableName());
System.out.print(pojoClass.getEntryTime());
System.out.print(pojoClass.getProcessingTime());
System.out.println(pojoClass.getStatus());
// System.out.println(pojoClass.getprocessDuration());
}
System.out.print(pojoCol.size());
}
}
You have to use currentTimeMillis() function:
Before launch polling:
long start = System.currentTimeMillis();
After Polling execution:
long stop= System.currentTimeMillis();
Execution time is stop - start in milliseconds.
I believe System.currentTimeMillis is what you looking for.
long startTime = System.currentTimeMillis();
//
long endTime = System.currentTimeMillis();
System.out.println((endTime - startTime) + "ms");
java.util.Date date = new java.util.Date();
Timestamp start = new Timestamp(date.getTime());
//process
java.util.Date date1 = new java.util.Date();
Timestamp end = new Timestamp(date1.getTime());
long start = System.currentTimeMillis();
rs = st.executeQuery( "select * from msg_new_to_bde" );
long stop= System.currentTimeMillis();
System.out.println("execution time: " +stop-start + " ms");
long start = System.nanoTime();
timeThisMethod();
long end = System.nanoTime();
long howLongDidItTake = end - start;
This method is more precise then System.currentTimeMillis()
Citation from java API :
Returns the current value of the most precise available system timer,
in nanoseconds.
Thank you in advance for your help. I am developing a java based tool that is preforming some database work. I have a very simple problem. For some reason the time reported to complete the task is incorrect.
public static void makeDatabaseThreaded() throws IOException, InterruptedException {
final long startTime = System.nanoTime();
ArrayList<String> tablesMade = new ArrayList<>();
File rootDirectory = root;
String[] files = rootDirectory.list();
double percentDone = 0;
double numOfTablesMade = 0;
double numberOfTables = 62.0;
DatabaseBuilderThread lastThread = null;
for (int i = 0; i <= files.length - 1; i++) {
if (!files[i].contains(".csv")) {
continue;
}
File file = new File(rootDirectory + File.separator + files[i]);
String tableName = getTableNameFromFile(file);
if (!tablesMade.contains(tableName)) {
tablesMade.add(tableName);
DatabaseBuilderThread thread = new DatabaseBuilderThread(i, file);
lastThread = thread;
thread.start();
threadsRunning++;
numOfTablesMade++;
percentDone = (int) (100.0 * (numOfTablesMade) / (numberOfTables));
while (threadsRunning > 10) {
Thread.sleep(1000);
}
System.out.println(percentDone + "% done. Making Table For File: " + file.getName());
}
}
//Make Sure all threads are done
lastThread.join();
final long endTime = System.nanoTime();
final long duration = endTime - startTime;
Time time = new Time(duration);
System.out.println("Done Making The Database. It took " + time.toString());
}
The program reports that it worked about twice as long at it truly did for the cases that I ran.
Thanks
System.nanoTime() returns time values in nanoseconds. Time() takes a value in milliseconds as a parameter. This would throw your time value off by a factor of 10^-6.
Time takes milliseconds as a constructor parameter, where as nanoTime() gives you nanoseconds precision, could that be the problem?
discussion here: System.currentTimeMillis vs System.nanoTime