+ 2

How do I get time in seconds since last frame? (Delta time)

I am developing a game which there is no frame cap meaning it can run in 200 fps and in 40 fps, this is why I need delta time. Now I've been trying to implement it but it didn't work. Here is my code in the run() method (override of Runnable): running = true; Time.Start = System.currentTimeMillis() / 1000; while (running) { update(); render(); Time.Previous = (System.currentTimeMillis() - Start) / 1000; } And here is my "Time" class: public class Time { public static float Delta() { return (System.currentTimeMillis() / 1000.0f - Start - Previous); } public static float Elapsed() { return (System.currentTimeMillis() / 1000.0f - Start); } public static long Start; public static long Previous; } Note that I am trying to get delta time in seconds in float. Thanks anyone for helping.

28th Dec 2020, 11:31 AM
Frumkin
Frumkin - avatar
1 Answer
+ 3
Nowhere in your code do you update the long Start. Essentially calculating the elapsed time from the start of the program -> current time. To compute the elapsed time, it should have a start and an end variable: public static void captureDeltaTime() { long start = System.currentTimeMillis(); slowCode(); long end = System.currentTimeMillis() - start; // Delta time in ms float seconds = end / 1000.0f; // Delta time in s converted to float System.out.println("Elapsed time in seconds: " + seconds); } By only setting the long "start" at the beginning, it will not correctly calculate the delta.
28th Dec 2020, 3:48 PM
Maru
Maru - avatar