简体   繁体   English

Java - 为什么这个基本的滴答类耗尽了这么多cpu?

[英]Java - Why does this basic ticking class use up so much cpu?

Details: For a lot the programs that I develop I use this code (or some slight variant) to "tick" a method every so often, set to the varaible tps (if set to 32 it calls the method tick 32 times every second). 细节:我开发的程序很多我使用这个代码(或一些轻微的变体)来经常“勾选”一个方法,设置为可变tps(如果设置为32,它每秒调用方法滴答32次) 。 Its very essential so I can't remove it from my code as animations and various other parts will break. 它非常重要所以我无法将其从我的代码中删除,因为动画和各种其他部分将会破坏。

Unfortunately it seems to use a sizable amount of cpu usage for a reason I can't figure out. 不幸的是,似乎使用了相当数量的CPU使用,这是我无法弄清楚的原因。 A while back I was thinking about using thread.sleep() to fix this issue but according to this post ; 前段时间我正在考虑使用thread.sleep()来解决这个问题,但根据这篇文章 ; it's rather innacurate which makes it unfeasible as this requires reasonably accurate timing. 它是相当空洞的,这使得它不可行,因为这需要合理准确的时间。

It doesn't use that much cpu, around 6-11% cpu for a ryzen 1700 in my admittedly short testing, but it's still quite a lot considering how little it's doing. 在我不可否认的短测试中,它没有使用那么多的CPU,大约6-11%的cpu用于ryzen 1700,但考虑到它做得有多少,它仍然相当多。 Is there a less cpu intensive method of completing this? 有没有一个较少的CPU密集的方法来完成这个? Or will the timing be to innacurate for regular usage. 或者将时间安排为经常使用。

public class ThreadTest {

    public ThreadTest() {
        int tps = 32;

        boolean threadShouldRun = true;
        long lastTime = System.nanoTime();
        double ns = 1000000000 / tps;
        double delta = 0;
        long now;

        while (threadShouldRun) {
            now = System.nanoTime();

            delta += (now - lastTime) / ns;
            lastTime = now;

            while ((delta >= 1) && (threadShouldRun)) {
                tick();
                delta--;
            }
        }
    }

    public void tick() {

    }

    public static void main(String[] args) {
        new ThreadTest();
    }
}

Basic summary: The code above uses 6-11% cpu with a ryzen 1700, is there a way in java to accomplish the same code with less cpu usage and keeping reasonable timing when executing code a certain amount of times per second. 基本摘要:上面的代码使用6-11%的cpu和ryzen 1700,在java中有一种方法可以用更少的cpu使用来完成相同的代码,并且在每秒执行一定次数的代码时保持合理的时间。

One easy alternative that shouldn't use as much CPU is to use a ScheduledExecutorService . 一个不应该使用尽可能多的CPU的简单替代方法是使用ScheduledExecutorService For example: 例如:

public static void main(String[] args) {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    executor.scheduleAtFixedRate(() -> {

    }, 0, 31250, TimeUnit.MICROSECONDS);
}

Note that 31250 represents the value of 1/32 seconds converted to microseconds, as that parameter accepts a long . 请注意, 31250表示转换为微秒的1/32秒的值,因为该参数接受long

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM