如何生成计算运行时间的循环?

2024-09-21 01:27:09 发布

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

我正在用python3制作一个简单的客户机/服务器程序,在客户机中我想要一个时钟或运行时间的打印输出。我试图使它在一个循环中,从程序的开始,但在一个线程中,所以其余的代码继续进行。你知道吗

    class time_thread():
        def run(self):

            loop = 0

            while (zetime > -1):
                print(zetime);
                zetime = zetime + 1;
    time_thread.start()
zetime = 0

这是我目前所拥有的,但它不起作用。上面写着:

time_thread has no attribute start()

我是新手,以前没用过线程,所以我不知道该怎么做。有更好的办法吗?你知道吗


Tags: 代码程序客户机timedef时间时钟线程
3条回答

首先,要使用Thread模块,必须在类上继承类Thread,这样就可以使用像start这样的方法。 要计算时间,可以使用datetime。你知道吗


from datetime import datetime
from time import sleep

start_time  = datetime.now()   
sleep(5) # code that you want to calculate.
end_time = datetime.now()   
print(end_time - start_time)   


把这个放好

假设你定义了一个函数,比如:

import time, sys
def elapsed_time(time_start):
    ''' time_start: a time.time()
        Goal: print the elapsed time since time_start '''
    # Allow to stop the counting once bool_time = False in the main program
    global bool_elapsed_time
    # loop while the condition 
    while bool_elapsed_time == True:
        # Note: erase and write below does not work in spyder but in a shell yes
        print ("Elapsed time: {} seconds".format(int(time.time() - time_start))),
        sys.stdout.flush()
        print ("\r"),
        time.sleep(1)
    # erase the line with elapsed time to clean the shell at the end
    sys.stdout.flush()
    print ("\r"),

然后在程序中:

import threading
bool_elapsed_time = True
t = threading.Thread(name='child procs', target=elapsed_time, args=(time.time(),))
t.start()
## Here add the job you want to do as an example:
time.sleep(10)
bool_elapsed_time = False #to stop the elapsed time printing

你应该做你想做的工作。你知道吗

注意:我使用了Python2.7,所以它可能与3.x略有不同

我想这就是你想要的:

import time, sys

zetime = 0
while (zetime > -1):
    sys.stdout.write("\r" + str(zetime))
    sys.stdout.flush()
    time.sleep(1)
    zetime = zetime + 1;

相关问题 更多 >

    热门问题