XiaMoHuaHuo_CN's Blog

| Loading...

Bukkit插件—计算服务器TPS

2022/6/5 教程

CraftBukkit没内置TPS接口,所以整了个TPS计算

前置代码

先新创建个类,比如我这个叫ServerTPS,往里面塞计算器

public class ServerTPS implements Runnable {
    public static final long[] TICKS = new long[600];
    public static int TICK_COUNT = 0;

    public static double getTPS() {
        return getTPS(100);
    }

    public static double getTPS(int ticks) {
        if (TICK_COUNT < ticks) {
            return 20.0D;
        }
        int target = (TICK_COUNT - 1 - ticks) % TICKS.length;
        long elapsed = System.currentTimeMillis() - TICKS[target];

        return ticks / (elapsed / 1000.0D);
    }

    public static long getElapsed(int tickID) {
        long time = TICKS[(tickID % TICKS.length)];
        return System.currentTimeMillis() - time;
    }

    public void run() {
        TICKS[(TICK_COUNT % TICKS.length)] = System.currentTimeMillis();
        TICK_COUNT += 1;
    }
}

然后再在主类的**onEnable()**里面调用

// 我这里类名叫ServerTPS,所以用的是new ServerTPS()
// 用的时候注意改成自己的类名
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new ServerTPS(), 100L, 1L);

使用

获得当前TPS

// 记得引入类
import example.ServerTPS;

ServerTPS.getTPS();

获取相对滞后程度

// 记得引入类
import example.ServerTPS;

ServerTPS.getElapsed()

文章地址:https://huahuo-cn.tk/2022/06/05/Bukkit插件—计算服务器TPS/

本站除特殊声明,均采用CC-BY-SA-4.0协议
详情请见:CC-BY-SA-4.0
img_show