[Solved] Executing a method X number of times per second in Java


To show something like “fps”:

public static void main(String[] args) {
    while (true) callMethod();
}

private static long lastTime = System.currentTimeMillis();
public static void callMethod() {
    long now = System.currentTimeMillis();
    long last = lastTime;
    lastTime = now;

    double fps = 1000 / (double)(now - last);
    System.out.println(fps);
}

You might have to add some sleeps, because otherwise the difference between two steps is just too small, the fps will be “Infinity”.

The requirement for 30 times a second is something entirely different. As I said in my comment already that is basically the exact opposite of fps since 30 times a second means exactly 30 fps, which means there is no need to calculate the fps because that is the original requirement.

Further note that “30 times a second” in itself is a generally bad requirement for at least two reasons:

  • is 1000 times a second okay? Does that fulfil the requirement
  • is running the method 30 times in the first millisecond and then waiting the remaining 999ms a useful solution to the problem?

3

solved Executing a method X number of times per second in Java