我怎么能有一个实时计时器,每秒钟更新一次,以查看我的程序运行了多少?python

2024-03-28 09:17:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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和编程的新手。如果打扰您,请原谅,提前谢谢您


Tags: in程序运行fortimerangesleepgreenred
2条回答

您不应该将time.sleepdiscord.py一起使用,因为它将停止您应该使用的整个botawait asyncio.sleep(1)

也可以创建此命令

import datetime as dt

bot.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它将告诉您它已经运行了多长时间

您可以通过多线程来实现这一点。您的函数随时间运行,两个函数在函数运行完成后立即终止:

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*i

t1 = threading.Thread(target=calc) 
t1.start() #starting a thread with the calc function
i = 1
while 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+1
t1.join() #terminate thread once calc function is done 
print('Done!')

相关问题 更多 >