Search Results

Search found 38 results on 2 pages for 'nanotime'.

Page 1/2 | 1 2  | Next Page >

  • Is System.nanoTime() consistent across threads?

    - by obvio171
    I want to count the time elapsed between two events in nanoseconds. To do that, I can use System.nanoTime() as mentioned here. The problem is that the two events are happening in different threads. Since nanoTime() doesn't return an absolute timestamp but instead can only be used to calculate time differences, I'd like to know if the values I get on the two different threads are consistent with the physical time elapsed between the two events.

    Read the article

  • java System.nanoTime is really slow. Is it possible to implement a high performance java profiler?

    - by willpowerforever
    I did a test and found the overhead of a function call to System.nanoTime() is at least 500 ns on my machine. Seemed that it is very hard to have a high performance java profiler. For enterprise software, suppose a function takes about 350 seconds and has 12,500,000,000 times of method calls. Therefore, the number of calls to System.nanoTime() is: 12,500,000,000 * 2 = 25,000,000,000 (one for start timestamp, one for end timestamp) And the overhead of System.nanoTime in total is: 500 ns * 25,000,000,000 = 500 * 25000 s = 12500000s. Note: all data from real case. Any better way to acquire the timestamp?

    Read the article

  • Simple rendering produces minor stutter

    - by Ben
    For some reason, this game loop renders the movement of a simple rectangle with no stuttering. double currTime; double prevTime = System.nanoTime() / NANO_TO_SEC; double FPSTIMER = System.nanoTime(); double maxTimeDiff = 100.0 / 1000.0; double delta = 1.0 / 60.0; int processes = 0, frames = 0; while(true){ currTime = System.nanoTime() / NANO_TO_SEC; if(currTime - prevTime > maxTimeDiff) prevTime = currTime; if(currTime >= prevTime){ process(); processes++; prevTime += delta; if(currTime < prevTime){ render(); frames++; } } else{ try{ Thread.sleep((long) (1000 * (prevTime - currTime))); } catch(Exception e){} } if(System.nanoTime() - FPSTIMER > 1000000000.0){ System.out.println("Process: " + (1000 / processes) + "ms FPS: " + (1000 / frames) + "ms"); processes = frames = 0; FPSTIMER += 1000000000.0; } } But for this game loop, I get really minor stuttering where the movement does not look smooth. long prevTime = System.currentTimeMillis(); long prevRenderTime = 0; long currRenderTime = 0; long delta = 0; long msPerTick = 1000 / 60; int frames = 0; int ticks = 0; double FPSTIMER = System.currentTimeMillis(); while (true){ long currTime = System.currentTimeMillis(); delta += (currTime - prevTime) / msPerTick; prevTime = currTime; while (delta >= 1){ ticks++; process(); delta -= 1; } prevRenderTime = System.currentTimeMillis(); render(); frames++; currRenderTime = System.currentTimeMillis(); try{ Thread.sleep((long) ((1000 / FPS) - (currRenderTime - prevRenderTime))); } catch(Exception e){} if(System.currentTimeMillis() - FPSTIMER > 1000.0){ System.out.println("Process: " + (1000.0 / ticks) + "ms FPS: " + (1000.0 / frames) + "ms"); ticks = frames = 0; FPSTIMER += 1000.0; } Is there any critical difference that I'm missing here? The one thing I noticed is that if I uncap the fps for the second game loop, the stuttering goes away. It doesn't make sense to me. Also, the second game loop came from Notch's Minicraft code with just my thread sleeping code added in.

    Read the article

  • Fastest way to pad a number in Java to a certain number of digits

    - by Martin
    Am trying to create a well-optimised bit of code to create number of X-digits in length (where X is read from a runtime properties file), based on a DB-generated sequence number (Y), which is then used a folder-name when saving a file. I've come up with three ideas so far, the fastest of which is the last one, but I'd appreciate any advice people may have on this... 1) Instantiate a StringBuilder with initial capacity X. Append Y. While length < X, insert a zero at pos zero. 2) Instantiate a StringBuilder with initial capacity X. While length < X, append a zero. Create a DecimalFormat based on StringBuilder value, and then format the number when it's needed. 3) Create a new int of Math.pow( 10, X ) and add Y. Use String.valueOf() on the new number and then substring(1) it. The second one can obviously be split into outside-loop and inside-loop sections. So, any tips? Using a for-loop of 10,000 iterations, I'm getting similar timings from the first two, and the third method is approximately ten-times faster. Does this seem correct? Full test-method code below... // Setup test variables int numDigits = 9; int testNumber = 724; int numIterations = 10000; String folderHolder = null; DecimalFormat outputFormat = new DecimalFormat( "#,##0" ); // StringBuilder test long before = System.nanoTime(); for ( int i = 0; i < numIterations; i++ ) { StringBuilder sb = new StringBuilder( numDigits ); sb.append( testNumber ); while ( sb.length() < numDigits ) { sb.insert( 0, 0 ); } folderHolder = sb.toString(); } long after = System.nanoTime(); System.out.println( "01: " + outputFormat.format( after - before ) + " nanoseconds" ); System.out.println( "Sanity check: Folder = \"" + folderHolder + "\"" ); // DecimalFormat test before = System.nanoTime(); StringBuilder sb = new StringBuilder( numDigits ); while ( sb.length() < numDigits ) { sb.append( 0 ); } DecimalFormat formatter = new DecimalFormat( sb.toString() ); for ( int i = 0; i < numIterations; i++ ) { folderHolder = formatter.format( testNumber ); } after = System.nanoTime(); System.out.println( "02: " + outputFormat.format( after - before ) + " nanoseconds" ); System.out.println( "Sanity check: Folder = \"" + folderHolder + "\"" ); // Substring test before = System.nanoTime(); int baseNum = (int)Math.pow( 10, numDigits ); for ( int i = 0; i < numIterations; i++ ) { int newNum = baseNum + testNumber; folderHolder = String.valueOf( newNum ).substring( 1 ); } after = System.nanoTime(); System.out.println( "03: " + outputFormat.format( after - before ) + " nanoseconds" ); System.out.println( "Sanity check: Folder = \"" + folderHolder + "\"" );

    Read the article

  • puzzled with java if else performance

    - by user1906966
    I am doing an investigation on a method's performance and finally identified the overhead was caused by the "else" portion of the if else statement. I have written a small program to illustrate the performance difference even when the else portion of the code never gets executed: public class TestIfPerf { public static void main( String[] args ) { boolean condition = true; long time = 0L; int value = 0; // warm up test for( int count=0; count<10000000; count++ ) { if ( condition ) { value = 1 + 2; } else { value = 1 + 3; } } // benchmark if condition only time = System.nanoTime(); for( int count=0; count<10000000; count++ ) { if ( condition ) { value = 1 + 2; } } time = System.nanoTime() - time; System.out.println( "1) performance " + time ); time = System.nanoTime(); // benchmark if else condition for( int count=0; count<10000000; count++ ) { if ( condition ) { value = 1 + 2; } else { value = 1 + 3; } } time = System.nanoTime() - time; System.out.println( "2) performance " + time ); } } and run the test program with java -classpath . -Dmx=800m -Dms=800m TestIfPerf. I performed this on both Mac and Linux Java with 1.6 latest build. Consistently the first benchmark, without the else is much faster than the second benchmark with the else section even though the code is structured such that the else portion is never executed because of the condition. I understand that to some, the difference might not be significant but the relative performance difference is large. I wonder if anyone has any insight to this (or maybe there is something I did incorrectly). Linux benchmark (in nano) performance 1215488 performance 2629531 Mac benchmark (in nano) performance 1667000 performance 4208000

    Read the article

  • Better way for calculating project euler's 2nd problem Fibonacci sequence)

    - by firephil
    object Problem_2 extends App { def fibLoop():Long = { var x = 1L var y = 2L var sum = 0L var swap = 0L while(x < 4000000) { if(x % 2 ==0) sum +=x swap = x x = y y = swap + x } sum } def fib:Int = { lazy val fs: Stream[Int] = 0 #:: 1 #:: fs.zip(fs.tail).map(p => p._1 + p._2) fs.view.takeWhile(_ <= 4000000).filter(_ % 2 == 0).sum } val t1 = System.nanoTime() val res = fibLoop val t2 = (System.nanoTime() - t1 )/1000 println(s"The result is: $res time taken $t2 ms ") } Is there a better functional way for calculating the fibonaci sequence and taking the sum of the the even values below 4million ? (projecteuler.net - problem 2) The imperative method is 1000x faster ?

    Read the article

  • Android Java: Way to effectively pause system time while debugging?

    - by TheMaster42
    In my project, I call nanoTime and use that to get a deltaTime which I pass to my entities and animations. However, while debugging (for example, stepping through my code), the system time on my phone is happily chugging along, so it's impossible to look at, say, two sequential frames of data in the debugger (since by the time I'm done looking at the first frame, the system time has continued to move ahead by seconds or even minutes). Is there a programming practice or method to pause the system clock (or a way for my code to intercept and fake my deltaTime) whenever I pause execution from the debugger? Additional Information: I'm using Eclipse Classic with the ADT plugin and a Samsung SII, coding in Java. My code invoking nanoTime: http://pastebin.com/0ZciyBtN I do all display via a Canvas object (2D sprites and animations).

    Read the article

  • Trying to write a loop that uses an OutputStream to write to a text file.

    - by Steve McLain
    I'm not a java programmer, I'm a VB programmer. I am doing this as part of an assignment, however, I'm not asking for help on something assignment related. I'd like to figure out how to get the OutputStreamWriter to work properly in this instance. I just want to capture the values I'm generating and place them into a text document. The file is generated, but only one entry exists, not the 40 I'm expecting. I could do this in a heartbeat with VB, but java feels very strange to me right now. Your help is appreciated. Thanks, Steve Here's the code: public static void main(String[] args){ long start, end; double result,difference; try {//OutputStream code assistance from http://tutorials.jenkov.com/java-io/outputstreamwriter.html OutputStream outputStream = new FileOutputStream("c:\\Temp\\output1.txt"); Writer out = new OutputStreamWriter(outputStream); for(int n=1; n<=20; n++){ //Calculate the Time for n^2. start = System.nanoTime(); //Add code to call method to calculate n^2 result = mN2(n); end = System.nanoTime(); difference = (end - start); //Output results to a file out.write("N^2 End time: " + end + " Difference: " + difference + "\n"); out.close(); } } catch (IOException e){ } try { OutputStream outputStream = new FileOutputStream("c:\\Temp\\output1.txt"); Writer out = new OutputStreamWriter(outputStream); for(int n=1; n<=20; n++){ //Calculate the Time for 2^n. start = System.nanoTime(); //Add code to call method to calculate 2^n result = m2N(n); end = System.nanoTime(); difference = (end - start); //Output results to a file out.write("N^2 End time: " + end + " Difference: " + difference + "\n"); out.close(); } } catch (IOException e){ } } //Calculate N^2 public static double mN2(double n) { n = n*n; return n; } //Calculate 2N public static double m2N (double n) { n = 2*n; return n; }

    Read the article

  • How to Handle frame rates and synchronizing screen repaints

    - by David Kroukamp
    I would first off say sorry if the title is worded incorrectly. Okay now let me give the scenario I'm creating a 2 player fighting game, An average battle will include a Map (moving/still) and 2 characters (which are rendered by redrawing a varying amount of sprites one after the other). Now at the moment I have a single game loop limiting me to a set number of frames per second (using Java): Timer timer = new Timer(0, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { long beginTime; //The time when the cycle begun long timeDiff; //The time it took for the cycle to execute int sleepTime; //ms to sleep (< 0 if we're behind) int fps = 1000 / 40; beginTime = System.nanoTime() / 1000000; //execute loop to update check collisions and draw gameLoop(); //Calculate how long did the cycle take timeDiff = System.nanoTime() / 1000000 - beginTime; //Calculate sleep time sleepTime = fps - (int) (timeDiff); if (sleepTime > 0) {//If sleepTime > 0 we're OK ((Timer)e.getSource()).setDelay(sleepTime); } } }); timer.start(); in gameLoop() characters are drawn to the screen ( a character holds an array of images which consists of their current sprites) every gameLoop() call will change the characters current sprite to the next and loop if the end is reached. But as you can imagine if a sprite is only 3 images in length than calling gameLoop() 40 times will cause the characters movement to be drawn 40/3=13 times. This causes a few minor anomilies in the sprited for some charcters So my question is how would I go about delivering a set amount of frames per second in when I have 2 characters on screen with varying amount of sprites?

    Read the article

  • How do I draw a scrolling background?

    - by droidmachine
    How can I draw background tile in my 2D side-scrolling game? Is that loop logical for OpenGL es? My tile 2400x480. Also I want to use parallax scrolling for my game. batcher.beginBatch(Assets.background); for(int i=0; i<100; i++) batcher.drawSprite(0+2400*i, 240, 2400, 480, Assets.backgroundRegion); batcher.endBatch(); UPDATE And thats my onDrawFrame.I'm sending deltaTime for fps control. public void onDrawFrame(GL10 gl) { GLGameState state = null; synchronized(stateChanged) { state = this.state; } if(state == GLGameState.Running) { float deltaTime = (System.nanoTime()-startTime) / 1000000000.0f; startTime = System.nanoTime(); screen.update(deltaTime); screen.present(deltaTime); } if(state == GLGameState.Paused) { screen.pause(); synchronized(stateChanged) { this.state = GLGameState.Idle; stateChanged.notifyAll(); } } if(state == GLGameState.Finished) { screen.pause(); screen.dispose(); synchronized(stateChanged) { this.state = GLGameState.Idle; stateChanged.notifyAll(); } } }

    Read the article

  • Multiple enemy array in LibGDX

    - by johnny-b
    I am trying to make a multiple enemy array, where every 30 secods a new bullet comes from a random point. And if the bullet is clicked it should disapear and a pop like an explosion should appear. And if the bullet hits the ball then the ball pops. so the bullet should change to a different sprite or texture. same with the ball pop. But all that happens is the bullet if touched pops and nothing else happens. And if modified then the bullet keeps flashing as the update is way too much. I have added COMMENTS in the code to explain more on the issues. below is the code. if more code is needed i will provide. Thank you public class GameRenderer { private GameWorld myWorld; private OrthographicCamera cam; private ShapeRenderer shapeRenderer; private SpriteBatch batcher; // Game Objects private Ball ball; private ScrollHandler scroller; private Background background; private Bullet bullet1; private BulletPop bPop; private Array<Bullet> bullets; // This is for the delay of the bullet coming one by one every 30 seconds. /** The time of the last shot fired, we set it to the current time in nano when the object is first created */ double lastShot = TimeUtils.nanoTime(); /** Convert 30 seconds into nano seconds, so 30,000 milli = 30 seconds */ double shotFreq = TimeUtils.millisToNanos(30000); // Game Assets private TextureRegion bg, bPop; private Animation bulletAnimation, ballAnimation; private Animation ballPopAnimation; public GameRenderer(GameWorld world) { myWorld = world; cam = new OrthographicCamera(); cam.setToOrtho(true, 480, 320); batcher = new SpriteBatch(); // Attach batcher to camera batcher.setProjectionMatrix(cam.combined); shapeRenderer = new ShapeRenderer(); shapeRenderer.setProjectionMatrix(cam.combined); // This is suppose to produce 10 bullets at random places on the background. bullets = new Array<Bullet>(); Bullet bullet = null; float bulletX = 00.0f; float bulletY = 00.0f; for (int i = 0; i < 10; i++) { bulletX = MathUtils.random(-10, 10); bulletY = MathUtils.random(-10, 10); bullet = new Bullet(bulletX, bulletY); AssetLoader.bullet1.flip(true, false); AssetLoader.bullet2.flip(true, false); bullets.add(bullet); } // Call helper methods to initialize instance variables initGameObjects(); initAssets(); } private void initGameObjects() { ball = GameWorld.getBall(); bullet1 = myWorld.getBullet1(); bPop = myWorld.getBulletPop(); scroller = myWorld.getScroller(); } private void initAssets() { bg = AssetLoader.bg; ballAnimation = AssetLoader.ballAnimation; bullet1Animation = AssetLoader.bullet1Animation; ballPopAnimation = AssetLoader.ballPopAnimation; } // This is to take the bullet away when clicked or touched. public void onClick() { for (int i = 0; i < bullets.size; i++) { if (bullets.get(i).getBounds().contains(0, 0)) bullets.removeIndex(i); } } private void drawBackground() { batcher.draw(bg1, background.getX(), background.getY(), background.getWidth(), backgroundMove.getHeight()); } public void render(float runTime) { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT); batcher.begin(); // Disable transparency // This is good for performance when drawing images that do not require // transparency. batcher.disableBlending(); drawBackground(); batcher.enableBlending(); // when the bullet hits the ball, it should be disposed or taken away and a ball pop sprite/texture should be put in its place if (bullet1.collides(ball)) { // draws the bPop texture but the bullet does not go just keeps going around, and the bPop texture goes. batcher.draw(AssetLoader.bPop, 195, 273); } batcher.draw(AssetLoader.ballAnimation.getKeyFrame(runTime), ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight()); // this is where i am trying to make the bullets come one by one, and if removed via the onClick() then bPop animation // should play but does not??? if(TimeUtils.nanoTime() - lastShot > shotFreq){ // Create your stuff for (int i = 0; i < bullets.size; i++) { bullets.get(i); batcher.draw(AssetLoader.bullet1Animation.getKeyFrame(runTime), bullet1.getX(), bullet1.getY(), bullet1.getOriginX(), bullet1.getOriginY(), bullet1.getWidth(), bullet1.getHeight(), 1.0f, 1.0f, bullet1.getRotation()); if (bullets.removeValue(bullet1, false)) { batcher.draw(AssetLoader.ballPopAnimation.getKeyFrame(runTime), bPop1.getX(), bPop1.getY(), bPop1.getWidth(), bPop1.getHeight()); } } /* Very important to set the last shot to now, or it will mess up and go full auto */ lastShot = TimeUtils.nanoTime(); } // End SpriteBatch batcher.end(); } } Thank you

    Read the article

  • Measuring the time to create and destroy a simple object

    - by portoalet
    From Effective Java 2nd Edition Item 7: Avoid Finalizers "Oh, and one more thing: there is a severe performance penalty for using finalizers. On my machine, the time to create and destroy a simple object is about 5.6 ns. Adding a finalizer increases the time to 2,400 ns. In other words, it is about 430 times slower to create and destroy objects with finalizers." How can one measure the time to create and destroy an object? Do you just do: long start = System.nanoTime(); SimpleObject simpleObj = new SimpleObject(); simpleObj.finalize(); long end = System.nanoTime(); long time = end - start;

    Read the article

  • How can I intercept a Tomcat request at socket level?

    - by Miguel Pardal
    Hi, I'm doing a performance study for a web application framework running on Apache Tomcat 6. I'm trying to measure the time overhead of handling HTTP requests. What I would like to do is: / // just before first request byte is read long t1 = System.nanoTime(); // request is processed... // just after final byte is written to response long t2 = System.nanoTime(); / Then I would compute the total time (t2 - t1). Is there a way to do this? Thanks for your help!

    Read the article

  • Is it possible to cast the Elapsed Time function to Integer?

    - by nuvio
    I have the following function: (def elapsedtime (with-out-str (time (run-my-function)))) and I was wondering if is possible to store only the integer value of the time, as I can only store a String at the moment.... Any suggestion? Thanks a lot UPDATE So I did use this: (defmacro nsecs [expr] `(let [start# (. System (nanoTime))] ~expr (- (. System (nanoTime)) start#))) And then modified this: (def elapsedtime (nsecs (run-my-function argument1 argument2))) but doesn't work, what am I doing wrong? "Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Wrong number of args (1) passed to: main$fn--105$nsecs"

    Read the article

  • Android OpenGL deltaTime Measure issue

    - by droidmachine
    I'm measuring deltaTime like that: deltaTime = (System.nanoTime()-startTime) / 1000000000.0f; startTime = System.nanoTime(); But I'm always getting different float values and because of that my game is stuttering.What can be the problem of that? 09-03 03:51:59.219: D/a(21807): 0.017184043 09-03 03:51:59.234: D/a(21807): 0.016405167 09-03 03:51:59.249: D/a(21807): 0.018071748 09-03 03:51:59.269: D/a(21807): 0.015293334 09-03 03:51:59.284: D/a(21807): 0.016080335 09-03 03:51:59.299: D/a(21807): 0.018669458 09-03 03:51:59.314: D/a(21807): 0.014720625 09-03 03:51:59.334: D/a(21807): 0.01605596 09-03 03:51:59.349: D/a(21807): 0.017086169

    Read the article

  • Random movement of wandering monsters in x & y axis in LibGDX

    - by Vishal Kumar
    I am making a simple top down RPG game in LibGDX. What I want is ... the enemies should wander here and there in x and y directions in certain interval so that it looks natural that they are guarding something. I spend several hours doing this but could not achieve what I want. After a long time of coding, I came with this code. But what I observed is when enemies come to an end of x or start of x or start of y or end of y of the map. It starts flickering for random intervals. Sometimes they remain nice, sometimes, they start flickering for long time. public class Enemy extends Sprite { public float MAX_VELOCITY = 0.05f; public static final int MOVING_LEFT = 0; public static final int MOVING_RIGHT = 1; public static final int MOVING_UP = 2; public static final int MOVING_DOWN = 3; public static final int HORIZONTAL_GUARD = 0; public static final int VERTICAL_GUARD = 1; public static final int RANDOM_GUARD = 2; private float startTime = System.nanoTime(); private static float SECONDS_TIME = 0; private boolean randomDecider; public int enemyType; public static final float width = 30 * World.WORLD_UNIT; public static final float height = 32 * World.WORLD_UNIT; public int state; public float stateTime; public boolean visible; public boolean dead; public Enemy(float x, float y, int enemyType) { super(x, y); state = MOVING_LEFT; this.enemyType = enemyType; stateTime = 0; visible = true; dead = false; boolean random = Math.random()>=0.5f ? true :false; if(enemyType == HORIZONTAL_GUARD){ if(random) velocity.x = -MAX_VELOCITY; else velocity.x = MAX_VELOCITY; } if(enemyType == VERTICAL_GUARD){ if(random) velocity.y = -MAX_VELOCITY; else velocity.y = MAX_VELOCITY; } if(enemyType == RANDOM_GUARD){ //if(random) //velocity.x = -MAX_VELOCITY; //else //velocity.y = MAX_VELOCITY; } } public void update(Enemy e, float deltaTime) { super.update(deltaTime); e.stateTime+= deltaTime; e.position.add(velocity); // This is for updating the Animation for Enemy Movement Direction. VERY IMPORTANT FOR REAL EFFECTS updateDirections(); //Here the various movement methods are called depending upon the type of the Enemy if(e.enemyType == HORIZONTAL_GUARD) guardHorizontally(); if(e.enemyType == VERTICAL_GUARD) guardVertically(); if(e.enemyType == RANDOM_GUARD) guardRandomly(); //quadrantMovement(e, deltaTime); } private void guardHorizontally(){ if(position.x <= 0){ velocity.x= MAX_VELOCITY; velocity.y= 0; } else if(position.x>= World.mapWidth-width){ velocity.x= -MAX_VELOCITY; velocity.y= 0; } } private void guardVertically(){ if(position.y<= 0){ velocity.y= MAX_VELOCITY; velocity.x= 0; } else if(position.y>= World.mapHeight- height){ velocity.y= -MAX_VELOCITY; velocity.x= 0; } } private void guardRandomly(){ if (System.nanoTime() - startTime >= 1000000000) { SECONDS_TIME++; if(SECONDS_TIME % 5==0) randomDecider = Math.random()>=0.5f ? true :false; if(SECONDS_TIME>=30) SECONDS_TIME =0; startTime = System.nanoTime(); } if(SECONDS_TIME <=30){ if(randomDecider && position.x >= 0) velocity.x= -MAX_VELOCITY; else{ if(position.x < World.mapWidth-width) velocity.x= MAX_VELOCITY; else velocity.x= -MAX_VELOCITY; } velocity.y =0; } else{ if(randomDecider && position.y >0) velocity.y= -MAX_VELOCITY; else velocity.y= MAX_VELOCITY; velocity.x =0; } /* //This is essential so as to keep the enemies inside the boundary of the Map if(position.x <= 0){ velocity.x= MAX_VELOCITY; //velocity.y= 0; } else if(position.x>= World.mapWidth-width){ velocity.x= -MAX_VELOCITY; //velocity.y= 0; } else if(position.y<= 0){ velocity.y= MAX_VELOCITY; //velocity.x= 0; } else if(position.y>= World.mapHeight- height){ velocity.y= -MAX_VELOCITY; //velocity.x= 0; } */ } private void updateDirections() { if(velocity.x > 0) state = MOVING_RIGHT; else if(velocity.x<0) state = MOVING_LEFT; else if(velocity.y>0) state = MOVING_UP; else if(velocity.y<0) state = MOVING_DOWN; } public Rectangle getBounds() { return new Rectangle(position.x, position.y, width, height); } private void quadrantMovement(Enemy e, float deltaTime) { int temp = e.getEnemyQuadrant(e.position.x, e.position.y); boolean random = Math.random()>=0.5f ? true :false; switch(temp){ case 1: velocity.x = MAX_VELOCITY; break; case 2: velocity.x = MAX_VELOCITY; break; case 3: velocity.x = -MAX_VELOCITY; break; case 4: velocity.x = -MAX_VELOCITY; break; default: if(random) velocity.x = MAX_VELOCITY; else velocity.y =-MAX_VELOCITY; } } public float getDistanceFromPoint(float p1,float p2){ Vector2 v1 = new Vector2(p1,p2); return position.dst(v1); } private int getEnemyQuadrant(float x, float y){ Rectangle enemyQuad = new Rectangle(x, y, 30, 32); if(ScreenQuadrants.getQuad1().contains(enemyQuad)) return 1; if(ScreenQuadrants.getQuad2().contains(enemyQuad)) return 2; if(ScreenQuadrants.getQuad3().contains(enemyQuad)) return 3; if(ScreenQuadrants.getQuad4().contains(enemyQuad)) return 4; return 0; } } Is there a better way of doing this. I am new to game development. I shall be very grateful to any help or reference.

    Read the article

  • Problems with createImage(int width, int height)

    - by Jonathan
    I have the following code, which is run every 10ms as part of a game: private void gameRender() { if(dbImage == null) { //createImage() returns null if GraphicsEnvironment.isHeadless() //returns true. (java.awt.GraphicsEnvironment) dbImage = createImage(PWIDTH, PHEIGHT); if(dbImage == null) { System.out.println("dbImage is null"); //Error recieved return; } else dbg = dbImage.getGraphics(); } //clear the background dbg.setColor(Color.white); dbg.fillRect(0, 0, PWIDTH, PHEIGHT); //draw game elements... if(gameOver) { gameOverMessage(dbg); } } The problem is that it enters the if statement which checks for the Image being null, even after I attempt to define the image. I looked around, and it seems that createImage() will return null if GraphicsEnvironment.isHeadless() returns true. I don't understand exactly what the isHeadless() method's purpose is, but I thought it might have something to do with the compiler or IDE, so I tried on two, both of which get the same error (Eclipse, and BlueJ). Anyone have any idea what the source of the error is, and how I might fix it? Thanks in advance Jonathan ................................................................... EDIT: I am using java.awt.Component.createImage(int width, int height). The purpose of this method is to ensure the creation of, and edit an Image that will contain the view of the player of the game, that will later be drawn to the screen by means of a JPanel. Here is some more code if this helps at all: public class Sim2D extends JPanel implements Runnable { private static final int PWIDTH = 500; private static final int PHEIGHT = 400; private volatile boolean running = true; private volatile boolean gameOver = false; private Thread animator; //gameRender() private Graphics dbg; private Image dbImage = null; public Sim2D() { setBackground(Color.white); setPreferredSize(new Dimension(PWIDTH, PHEIGHT)); setFocusable(true); requestFocus(); //Sim2D now recieves key events readyForTermination(); addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { testPress(e.getX(), e.getY()); } }); } //end of constructor private void testPress(int x, int y) { if(!gameOver) { gameOver = true; //end game at mousepress } } //end of testPress() private void readyForTermination() { addKeyListener( new KeyAdapter() { public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if((keyCode == KeyEvent.VK_ESCAPE) || (keyCode == KeyEvent.VK_Q) || (keyCode == KeyEvent.VK_END) || ((keyCode == KeyEvent.VK_C) && e.isControlDown()) ) { running = false; //end process on above list of keypresses } } }); } //end of readyForTermination() public void addNotify() { super.addNotify(); //creates the peer startGame(); //start the thread } //end of addNotify() public void startGame() { if(animator == null || !running) { animator = new Thread(this); animator.start(); } } //end of startGame() //run method for world public void run() { while(running) { long beforeTime, timeDiff, sleepTime; beforeTime = System.nanoTime(); gameUpdate(); //updates objects in game (step event in game) gameRender(); //renders image paintScreen(); //paints rendered image to screen timeDiff = (System.nanoTime() - beforeTime) / 1000000; sleepTime = 10 - timeDiff; if(sleepTime <= 0) //if took longer than 10ms { sleepTime = 5; //sleep a bit anyways } try{ Thread.sleep(sleepTime); //sleep by allotted time (attempts to keep this loop to about 10ms) } catch(InterruptedException ex){} beforeTime = System.nanoTime(); } System.exit(0); } //end of run() private void gameRender() { if(dbImage == null) { dbImage = createImage(PWIDTH, PHEIGHT); if(dbImage == null) { System.out.println("dbImage is null"); return; } else dbg = dbImage.getGraphics(); } //clear the background dbg.setColor(Color.white); dbg.fillRect(0, 0, PWIDTH, PHEIGHT); //draw game elements... if(gameOver) { gameOverMessage(dbg); } } //end of gameRender() } //end of class Sim2D Hope this helps clear things up a bit, Jonathan

    Read the article

  • implementing gravity to projectile - delta time issue

    - by Murat Nafiz
    I'm trying to implement a simple projectile motion in Android (with openGL). And I want to add gravity to my world to simulate a ball's dropping realistically. I simply update my renderer with a delta time which is calculated by: float deltaTime = (System.nanoTime()-startTime) / 1000000000.0f; startTime = System.nanoTime(); screen.update(deltaTime); In my screen.update(deltaTime) method: if (isballMoving) { golfBall.updateLocationAndVelocity(deltaTime); } And in golfBall.updateLocationAndVelocity(deltaTime) method: public final static double G = -9.81; double vz0 = getVZ0(); // Gets initial velocity(z) double z0 = getZ0(); // Gets initial height double time = getS(); // gets total time from act begin double vz = vz0 + G * deltaTime; // calculate new velocity(z) double z = z0 - vz0 * deltaTime- 0.5 * G * deltaTime* deltaTime; // calculate new position time = time + deltaTime; // Update time setS(time); //set new total time Now here is the problem; If I set deltaTime as 0.07 statically, then the animation runs normally. But since the update() method runs as faster as it can, the length and therefore the speed of the ball varies from device to device. If I don't touch deltaTime and run the program (deltaTime's are between 0.01 - 0.02 with my test devices) animation length and the speed of ball are same at different devices. But the animation is so SLOW! What am I doing wrong?

    Read the article

  • Timeout Exceptions

    - by Raihan Jamal
    This is my below code, I am confuse why this thing is happening. In this code getLocationByIpTimeout is a method in which I am passing two things- one is the ip address and second is the timeout. So I will get the timeout exception if the response is not getting back in under 5 ms. So when I ran this below code, I am getting few timeout exceptions but the most important thing that I am confuse is if I am getting timeout exceptions (time taken to get the response is greater than 5 ms) then why the program is entering in that if loop in which I am having difference 5. What can be the possible reason for this? It is because of catch block?? Any suggestions will be appreciated. long runs =10000; long difference = 0; while(runs > 0) { String ipAddress = generateIPAddress(); long start_time = System.nanoTime(); try { resp = PersonalizationGeoLocationServiceClientHelper.getLocationByIpTimeout(ipAddress, 5); } catch (TimeoutException e) { System.out.println("Timeout Exception"); } long end_time = System.nanoTime(); if(resp == null || (resp.getLocation() == null)) { difference = 0; } else if(resp.getLocation() != null) { difference = (end_time - start_time)/1000000; } if(difference> 5) { System.out.println("Debug"); } }

    Read the article

  • Do running times match with O(nlogn)?

    - by user472221
    Hi I have written a class(greedy strategy) that at first i used sort method which has O(nlogn) Collections.sort(array, new SortingObjectsWithProbabilityField()); and then i used the insert method of binary search tree which takes O(h) and h here is the tree height. for different n ,the running time will be : n,running time 17,515428 33,783340 65,540572 129,1285080 257,2052216 513,4299709 which I think is not correct because for increasing n , the running time should almost increase. This method will take the running time: Exponent = -1; for(int n = 2;n<1000;n+=Math.pow(2,exponent){ for (int j = 1; j <= 3; j++) { Random rand = new Random(); for (int i = 0; i < n; i++) { Element e = new Element(rand.nextInt(100) + 1, rand.nextInt(100) + 1, 0); for (int k = 0; k < i; k++) { if (e.getDigit() == randList.get(k).getDigit()) { e.setDigit(e.getDigit() + 1); } } randList.add(e); } double sum = 0.0; for (int i = 0; i < randList.size(); i++) { sum += randList.get(i).getProbability(); } for (Element i : randList) { i.setProbability(i.getProbability() / sum); } //Get time. long t2 = System.nanoTime(); GreedyVersion greedy = new GreedyVersion((ArrayList<Element>) randList); long t3 = System.nanoTime(); timeForGreedy = timeForGreedy + t3 - t2; } System.out.println(n + "," + "," + timeForGreedy/3 ); exponent++; } thanks

    Read the article

  • ?????????????JVM??????|WebLogic Channel|??????

    - by ???02
    JRockit JVM????????????????????????????????????????????????????????????????????????????????????????????    ?JVM????????????????    ?JVM???????????    ????????????????????    ?????????    ?JVM??????????????JVM????????????????????????????????????????????????????    * ?????????????????????????????    * ??????????????????????    * ???????????????(??????CPU??????)    * JVM????Java??????????????????????    * ????????????JVM???????JVM???JRockit JVM???????????JRockit JVM???????????????????????????JIT?????JVM?????JVM?????????????????????????????·?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????JVM???????????????????????????????????????JVM???????????????JVM??????????????????????????????-Xverbose:codegen?????????????????????????????????????????????????????    *???????    *???????    *?????·?????????    *???????????????????????????????????JIT?????????????????????????JVM???????????????????????????????????????????????????-Xverbose:opt??????????????????????????????????????????????????????????????????????·??????????????????????????????????????????????????????????????????????????????????·????·????????????????·??????????????????????????????????????????System.nanoTime()???System.currentTimeMillis()??????????????????????????????????????????????????????????????????????????JVM?????????????????????????????????????????????JVM????????????????????·??????·??????????????????????????????????JVM??????????????????????????????????????·????5.2??????????????????????????????????????????????????Java??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? Java?????????????????????????????????·????·????????????????????Oracle JRockit ????????(????28)?Oracle JRockit????????????????·??? ?Oracle JRockit???????·??????·??? ?Oracle JRockit????·????·??·???·???????????·??????

    Read the article

  • How do I create a partial function with generics in scala?

    - by Matteo Caprari
    Hello. I'm trying to write a performance measurements library for Scala. My idea is to transparently 'mark' sections so that the execution time can be collected. Unfortunately I wasn't able to bend the compiler to my will. An admittedly contrived example of what I have in mind: // generate a timing function val myTimer = mkTimer('myTimer) // see how the timing function returns the right type depending on the // type of the function it is passed to it val act = actor { loop { receive { case 'Int => val calc = myTimer { (1 to 100000).sum } val result = calc + 10 // calc must be Int self reply (result) case 'String => val calc = myTimer { (1 to 100000).mkString } val result = calc + " String" // calc must be String self reply (result) } Now, this is the farthest I got: trait Timing { def time[T <: Any](name: Symbol)(op: => T) :T = { val start = System.nanoTime val result = op val elapsed = System.nanoTime - start println(name + ": " + elapsed) result } def mkTimer[T <: Any](name: Symbol) : (() => T) => () => T = { type c = () => T time(name)(_ : c) } } Using the time function directly works and the compiler correctly uses the return type of the anonymous function to type the 'time' function: val bigString = time('timerBigString) { (1 to 100000).mkString("-") } println (bigString) Great as it seems, this pattern has a number of shortcomings: forces the user to reuse the same symbol at each invocation makes it more difficult to do more advanced stuff like predefined project-level timers does not allow the library to initialize once a data structure for 'timerBigString So here it comes mkTimer, that would allow me to partially apply the time function and reuse it. I use mkTimer like this: val myTimer = mkTimer('aTimer) val myString= myTimer { (1 to 100000).mkString("-") } println (myString) But I get a compiler error: error: type mismatch; found : String required: () => Nothing (1 to 100000).mkString("-") I get the same error if I inline the currying: val timerBigString = time('timerBigString) _ val bigString = timerBigString { (1 to 100000).mkString("-") } println (bigString) This works if I do val timerBigString = time('timerBigString) (_: String), but this is not what I want. I'd like to defer typing of the partially applied function until application. I conclude that the compiler is deciding the return type of the partial function when I first create it, chosing "Nothing" because it can't make a better informed choice. So I guess what I'm looking for is a sort of late-binding of the partially applied function. Is there any way to do this? Or maybe is there a completely different path I could follow? Well, thanks for reading this far -teo

    Read the article

  • Random generates same number in java

    - by user1613360
    This is my java code. import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; class search { private int numelem; private int[] input=new int[100]; public void setNumofelem() { System.out.println("Enter the total numebr of elements"); Scanner yz=new Scanner(System.in); numelem=yz.nextInt(); } public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { input[j]=rand.nextInt(max)+1; } } public void printinput() { int b=numelem,t=0; while(true) if(b!=0) { System.out.print(" "+input[t]); b--; t++; } else break; } } public class mycode { public static void main(String args[]) throws Exception { search a=new search(); a.setNumofelem(); a.randomnumber(); a.printinput(); } } Now the function randomnumber() just returns the same number.The function executes perfectly if I execute it as a separate java program but fails miserably if I call it using an object.I have also tried the following variations but nothing works everything return the same number. Variation 1: public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { TimeUnit.SECONDS.sleep(1); input[j]=rand.nextInt(max)+1; } } Variation 2: public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { rand.setSeed(System.nanoTime()); input[j]=rand.nextInt(max)+1; } } Variation 3: public void randomnumber() throws Exception { int max=500,min=1,n=numelem; Random rand = new Random(); for (int j=0;j < n;j++) { TimeUnit.SECONDS.sleep(1); rand.setSeed(System.nanoTime()); input[j]=rand.nextInt(max)+1; } } Sample input/Output: Enter the number of elements: 5 23 23 23 23 23 23

    Read the article

  • Thread class closing from other Class (Activity) with protected void onStop() Android

    - by user1761337
    I have a Problem with Closing the Thread. I will Closing the Thread with onStop,onPause and onDestroy. This is my Source in the Activity Class: @Override protected void onStop(){ super.onStop(); finish(); } @Override protected void onPause() { super.onPause(); finish(); } @Override public void onDestroy() { this.mWakeLock.release(); super.onDestroy(); } And the Thread Class: public class GameThread extends Thread { private SurfaceHolder mSurfaceHolder; private Handler mHandler; private Context mContext; private Paint mLinePaint; private Paint blackPaint; //for consistent rendering private long sleepTime; //amount of time to sleep for (in milliseconds) private long delay=1000/30; //state of game (Running or Paused). int state = 1; public final static int RUNNING = 1; public final static int PAUSED = 2; public final static int STOPED = 3; GameSurface gEngine; public GameThread(SurfaceHolder surfaceHolder, Context context, Handler handler,GameSurface gEngineS){ //data about the screen mSurfaceHolder = surfaceHolder; mHandler = handler; mContext = context; gEngine=gEngineS; } //This is the most important part of the code. It is invoked when the call to start() is //made from the SurfaceView class. It loops continuously until the game is finished or //the application is suspended. private long beforeTime; @Override public void run() { //UPDATE while (state==RUNNING) { Log.d("State","Thread is runnig"); //time before update beforeTime = System.nanoTime(); //This is where we update the game engine gEngine.Update(); //DRAW Canvas c = null; try { //lock canvas so nothing else can use it c = mSurfaceHolder.lockCanvas(null); synchronized (mSurfaceHolder) { //clear the screen with the black painter. //reset the canvas c.drawColor(Color.BLACK); //This is where we draw the game engine. gEngine.doDraw(c); } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } this.sleepTime = delay-((System.nanoTime()-beforeTime)/1000000L); try { //actual sleep code if(sleepTime>0){ this.sleep(sleepTime); } } catch (InterruptedException ex) { Logger.getLogger(GameThread.class.getName()).log(Level.SEVERE, null, ex); } while (state==PAUSED){ Log.d("State","Thread is pausing"); try { this.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }} How i can close the Thread from Activity Class??

    Read the article

  • JAVA BubbleSort Output Plotting

    - by John Smith
    I'm not sure how to plot the output I get with my run time results for BubbleSort. Here's the thing: I've written a working BubbleSort algorithm that does exactly as it should. But I wish to plot the output, to show the following: Best Case, Worst Case, Average Case ... How would I go about plotting it on a graph? Here is the code: public class BubbleSort { static double bestTime = 10000000, worstTime = 0; public static void main(String[] args) { int BubArray[] = new int[]{13981, 6793, 2662, 10986, 733, ... #1000 integers}; System.out.println("Unsorted List Before Bubble Sort"); for(int a = 0; a < BubArray.length; a++){ System.out.print(BubArray[a] + " "); } System.out.println("\n Bubble Sort Execution ..."); for(int i=0; i<10000;i++) { bubbleSortTimeTaken(BubArray, i); } int itrs = bubbleSort(BubArray); System.out.println(""); System.out.println("Array After Bubble Sort"); System.out.println("Moves Taken for Sort : " + itrs + " Moves."); System.out.println("BestTime: " + bestTime + " WorstTime: " + worstTime); System.out.print("Sorted Array: \n"); for(int a = 0; a < BubArray.length; a++){ System.out.print(BubArray[a] + " "); } } private static int bubbleSort(int[] BubArray) { int z = BubArray.length; int temp = 0; int itrs = 0; for(int a = 0; a < z; a++){ for(int x=1; x < (z-a); x++){ if(BubArray[x-1] > BubArray[x]){ temp = BubArray[x-1]; BubArray[x-1] = BubArray[x]; BubArray[x] = temp; } itrs++; } } return itrs; } public static void bubbleSortTimeTaken(int[] BubArray, int n) { long startTime = System.nanoTime(); bubbleSort(BubArray); double timeTaken = (System.nanoTime() - startTime)/1000000d; if (timeTaken > 0) { worstTime = timeTaken; } else if (timeTaken < bestTime) { bestTime = timeTaken; } System.out.println(n + "," + timeTaken); } } The output are as the following ( execution number, time (nano/10^6): Unsorted List Before Bubble Sort 13981 6793 2662 .... #1000 integers Bubble Sort Execution ... 0, 18.319891 1, 4.728978 2, 3.670697 3, 3.648922 4, 4.161576 5, 3.824369 .... 9995, 4.331423 9996, 3.692473 9997, 3.709893 9998, 6.16055 9999, 4.32209 Array After Bubble Sort Moves Taken for Sort : 541320 Moves. BestTime: 1.0E7 WorstTime: 4.32209 Sorted Array: 10 11 17 24 57 60 83 128 141 145 ... #1000 integers I am looking for graphs to represent Average, Best and Worst case based on the output but my current graphs don't look correct. Any help would be appreciated, thanks.

    Read the article

1 2  | Next Page >