在Java中每秒执行方法X次 [英] Executing a method X number of times per second in Java

查看:895
本文介绍了在Java中每秒执行方法X次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是每秒执行X次给定的方法(例如每秒执行30次).在该刻度方法中,我应该显示当前速度(基本上显示FPS).

I have a task to execute a given method X times per second (example 30 times per second). Within that tick method, I should show the current speed (basically display FPS).

我什至不知道如何开始.尝试使用谷歌搜索,但并没有真正帮助.

I don't even know how to start. Tried googling but didn't really help.

推荐答案

要显示类似"fps"的内容:

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);
}

您可能必须添加一些睡眠,因为否则两个步骤之间的差异将太小,fps将为无穷大".

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

每秒30次的要求是完全不同的.正如我在评论中已经说过的那样,基本上与fps完全相反,因为每秒30次意味着恰好是30 fps,这意味着不需要计算fps,因为这是原始要求.

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.

进一步请注意,出于至少两个原因,每秒30次"本身通常是很糟糕的要求:

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

  • 每秒可以1000次吗?是否满足要求
  • 在第一毫秒内运行该方法30次,然后等待剩余的999ms是解决该问题的有用方法吗?

这篇关于在Java中每秒执行方法X次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆