简体   繁体   中英

Using timeit module in Python with function

I have created a script in Python to calculate X specified numbers of the prime number sequence, and this works just fine on its own.

However, I am looking to find how long it takes this script to run in the terminal, and I learned from the Internet that the timeit module was the best way to do this.

However, the description on Python's website and other questions concerning this are quite irrelevant to my case. Here is the code.

P = 2
Y = 1

def Main(P, Y):
    X = int(raw_input('choose number: '))
    while Y <= X:
        isprime = True
        for x in range(2, P - 1):
            if P % x == 0:
                isprime = False
        if isprime:
            print P
            Y += 1
        P += 1

Main(P, Y)

Basically, how would I use the timeit module in this situation, so that it will print out the numbers in the sequence (as the above code allows it to) and then prints out the time it takes to calculate the specified amount of numbers?

Would it be possible to do this without making large edits to the current code?

Using timeit for this will include time taken by the algorithm/function plus time taken by the user to pass the input and it's not good practice to include user input time while computing completion time of an algorithm/function.

So it is better to use the datetime module and avoid user input time as:

from datetime import datetime as dt
P = 2
Y = 1

def Main(P, Y):
    X = int(raw_input('choose number: '))
    t1 = dt.now() # Get function starting time
    # It is better to get starting time after user input because user can take any amount of time to pass the input
    while Y <= X:
        isprime = True
        for x in range(2, P - 1):
            if P % x == 0: 
                isprime = False
        if isprime:
            print P
            Y += 1
        P += 1
    t2 = dt.now() # Get function completion time
    print 'Total time taken = {} seconds'.format((t2-t1).total_seconds()) # Print time difference in seconds

Main(P, Y)

Still if you want to do it using timeit . Here is the code:

timeit.timeit('Main(P,Y)', 'from __main__ import Main,P,Y', number=1)

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