简体   繁体   中英

How do i analyze the running time of a function with a for loop with an if statement?

For example, let the function consist:

def myfunc():
    total = 0
    for i in range(0, n):
       total+=i
       if total >= n:
         return total
    return 0

What would the running time be?

I cant seem to figure out a way to analyze this problem.

You can define your own decorator, like this:

def timed_function(f):
    def wrapper(*args, **kwargs):
        import time
        start_time = time.time()
        result = f(*args, **kwargs)
        elapsed = time.time() - start_time
        print("{} took {} seconds to run.".format(f, elapsed))
        return result
    return wrapper


@timed_function
def adding():
    a = 0
    for i in range(10000000):
        a = a + 1
    return a

adding()

<function adding at 0x0000023711A0EE50> took 0.49866580963134766 seconds to run.

Edit: Maybe you just need the basics? Then import the time module, and measure before and after running your code, and then print the result. For example:

import time

start_time = time.time()

#your code goes here

end_time = time.time()
time_elapsed = end_time - start_time
print("Took", time_elapsed)

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