简体   繁体   English

在计时器在python中用尽之前完成一项任务

[英]Complete a task before the timer runs out in python

I have 2 functions, one is a countdown timer and another is basically the function that I want to execute within the time period. 我有2个功能,一个是倒数计时器,另一个基本上是我要在该时间段内执行的功能。

My code for the countdown timer is as follows: 我的倒数计时器代码如下:

def countdown(count):
   while count > 0:
       print(count)
       count -= 1
       time.sleep(1)
   return

My other function that I want to complete its execution before the timer runs out is as follows: 我想在计时器用尽之前完成其执行的其他功能如下:

def solution(imat, painter):
nrows, ncols = imat.shape # gets the total number of rows and columns from a text file
for r in range(nrows): 
    for c in range(ncols):
        if imat[r,c] == 1: # checks if there is a 1 in any index (row and column) in the text file
            painter.paint('square',r, c, 1) # square is the method it uses to print, i.e  in blocks, and 1 is basically the size of the block that prints 

My question now is that is it possible for me to run the solution function completely before the timer runs out? 我现在的问题是,是否有可能在计时器用完之前完全运行解决方案功能?

I have tried to use t1 = threading.Thread(target=countdown , args =(imat, painter)) in the solution function,, but it did not work. 我试图在解决方案函数中使用t1 = threading.Thread(target=countdown , args =(imat, painter)) ,但没有用。 The maximum value count can be set to is 20. 最大值计数可以设置为20。

The painter.paint(...) function runs at 160 commands, meaning there are a 160 1s in the text file, there is there is a way to reduce the number of commands that function takes to run? painter.paint(...)函数以160个命令运行,这意味着文本文件中有160个1s,有没有一种方法可以减少函数运行所需的命令数量?

Can the number of commands be reduced using threads? 可以使用线程减少命令数量吗?

All help will be highly appreciated. 所有帮助将不胜感激。

It looks like Peter Wood is probably on the money in that you are targeting the countdown function, but passing arguments for the solution function in your threading code. 看起来Peter Wood可能是在赚钱,因为您的目标是倒计时函数,但是在线程代码中传递了solution函数的参数。

However, if you simply want to time your code, this guide has some really good stuff in it on how to do so. 但是,如果您只是想对代码计时,则指南中有一些非常好的方法。 I personally love the line_profiler as it gives you the execution time of each individual line. 我个人喜欢line_profiler,因为它为您提供了每行的执行时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM