简体   繁体   中英

Check how long function is currently running Python

So lets say I have the function:

def f(x):
    for i in range(x):
        print(i**2)
    return x

I want to implement this:


print(f(99999999))

if f.runTime() > 0.1:
    #DoSomething()

So it will call the function, but will DoSomething() if f() is taking longer than 0.1s (even before f() returns!)

So no, the time module is not what I'm looking for.

As some people suggested, the good option here is using threads, you can check the documentation or this example .

If you don't want to get in there and your time checking must not be very precise, you can do like this:

import time
def f(x):
    start_time = time.time()
    for i in range(x):
        if time.time() - start_time < TIME_LIMIT:
            print(i**2)
        else:
            raise Exception('execution time exceded')
    return x

try:
   print(f(99999999))
except Exception as error:
   print(error)

this is a worse solution because it will lose some execution time while checking in each iteration, but you can try if this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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