如何使正确的服务器打勾? [英] How to make a proper server tick?

查看:57
本文介绍了如何使正确的服务器打勾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个在一段时间后更新的游戏服务器.

I am trying to make a game server which updates after a certain period.

import time
last_time = time.time()
tick = 1
time_since_last_update = 0
while True:
    new_time = time.time()
    dt = new_time - last_time
    time_since_last_update += dt
    last_time = new_time
    if time_since_last_update > tick:
        print("Magic happens")
        time_since_last_update = 0

当我做这件事时,python 在其中一个核心上消耗了 100% 的计算能力.我真的不明白为什么会发生这种情况以及如果可能的话如何解决这个问题.

When I do this thing, python consumes 100% computing power on one of the cores. I don't really understand why is this happening and how to fix this if possible.

推荐答案

插入 time.sleep(0.01) 以在每次轮询之间等待 10 毫秒,否则您的循环会持续轮询时间而不释放电源中央处理器.

Insert a time.sleep(0.01) to wait 10 millis between each time poll otherwise your loop polls time continuously without releasing power to the cpu.

那更好,只在需要时等待一次.如果发生巨大的 CPU 过载,等待时间可能为负,在这种情况下,可以同时触发 2 个操作.并不断重新计算目标时间,以避免浮动累积错误.

That is better, only waits once if needed. Should a huge CPU overload occur, the time to wait could be negative, and in that case 2 actions could be triggered at once. And targeted time is recomputed constantly to avoid float accumulation errors.

import time
start_time = time.time()
tick = 1.0  # 1 second

tick_count = 0

while True:
    new_time = time.time()
    tick_count += 1
    targeted_time = start_time + tick*tick_count

    time_to_wait = targeted_time - new_time

    if time_to_wait>0:
        time.sleep(time_to_wait)
    print("Magic happens,waited %f seconds" % time_to_wait)

这篇关于如何使正确的服务器打勾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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