我怎样才能有一个每秒更新一次的实时计时器来查看我的程序运行了多少?

有没有办法制作一个每秒更新一次的计时器,这样我就可以看到我的程序运行了多长时间。我尝试制作一个循环:


i = 0

for i in range(1000000):

    i += 1

    time.sleep(1)

然后我想将其打印到我的discord.py 机器人中。它是这样的:


async def on_ready():

    os.system('cls')

    print('', fg('red'))

    print(' _____ _                         ', fg('red'))

    print('|  ___| | __ _ _ __  _ __  _   _ ', fg('red'))

    print("| |_  | |/ _` | '_ \| '_ \| | | |", fg('red'))

    print('|  _| | | (_| | |_) | |_) | |_| |', fg('red'))

    print('|_|   |_|\__,_| .__/| .__/ \__, |', fg('red'))

    print('              |_|   |_|     |___/ ', fg('red'))

    print(f'Up-Time: {i}')

    print(f'Version: {version}', fg('blue'))

    print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~', fg('green'))

    print('[Server]: The Bot is online.', fg('green'))


“Up-Time”是我想要显示时间的地方,但是当我尝试运行它时,什么也没有显示。但是当我将 print(i) 放在循环下面时,它唯一做的就是打印出数字,而不运行实际的服务器。


如果解释不够好,我很抱歉,我对 StackOverFlow 和一般编程非常陌生。抱歉,如果打扰您,先谢谢您!


哆啦的时光机
浏览 153回答 2
2回答

ABOUTYOU

您可以通过多线程来完成此任务。您让函数与您的时间一起运行,并且函数运行完毕后两者都会立即终止:import threading import time def calc(): #this function generates the square of all numbers between 1 and 56000000    for i in range(1,56000000):    i*it1 = threading.Thread(target=calc) t1.start() #starting a thread with the calc functioni = 1while t1.is_alive(): #Check if the thread is alive    time.sleep(1)# print time after every second    print(f'Time elapsed ----------- {i}s')    i = i+1t1.join() #terminate thread once calc function is done print('Done!')

RISEBY

您永远不应该使用time.sleepwithdiscord.py因为它会停止您应该使用的整个机器人await asyncio.sleep(1)。您也可以创建此命令。import datetime as dtbot.launch_time = dt.datetime.utcnow()@bot.command()async def uptime(ctx):    delta_uptime = dt.datetime.utcnow() - bot.launch_time    hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)    minutes, seconds = divmod(remainder, 60)    days, hours = divmod(hours, 24)    await ctx.send(f"{days}d, {hours}h, {minutes}m, {seconds}s")现在您可以使用{prefix}uptime它来了解它已经运行了多长时间。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python