简体   繁体   中英

Difference in execution time for a query in Python

I am trying to print a prime palindrome which is greater or equal to a given number 't'

My code is-

from math import sqrt
#import sys
from time import time

def is_prime(t):
    flag=True
    if(t<2):
        return False
    for i in range(2,int(sqrt(t))+1):
        if t%i==0:
            flag=False
            break
    if flag==True:
        return True
    else:
        return False


def is_palindrome(t):
    flag=False
    string=str(t)
    length=len(string)
    count=0
    for i in range(0,length/2):
        if(string[i]==string[length-1-i]):
            count+=1
        else:
            break
    if count==length/2:
        return True
    else:
        return False

def start():
    t= int (raw_input())
    t0 = time()

    while(True):
        apple=is_prime(t)
        if(is_palindrome(t)):
            if(apple):            
                print t
                print "Execution time:", round(time()-t0, 3), "s"
                break
        t=t+1


start()

This code runs fine. In the start() function I have added a statement to calculate the execution time. For a test case- 99999 execution time is around 14.05s. But if I change the function start with the one below-

def start():
    t= int (raw_input())
    t0 = time()

    while(True):
        if(is_palindrome(t)):
            if(is_prime(t)):            
                print t
                print "Execution time:", round(time()-t0, 3), "s"
                break
        t=t+1

Then the execution time for same test case (99999) reduces to 1.3s. I am new to python. I cannot understand that by just assigning a new variable, how can execution time change so much? Kindly help.

The is_prime test is expensive. The is_palindrome test is much less expensive. In the faster case, you only compute is_prime if the number is a palindrome, resulting in many fewer calls to is_prime , so the program executes more quickly.

its not about assigning the variable. Run this example

def start2():
    t= int (raw_input())
    t0 = time()

    while(True):
        if(is_palindrome(t)):
            apple=is_prime(t)
            if(apple):            
                print t
                print "Execution time:", round(time()-t0, 3), "s"
                break
        t=t+1

It will take around 1.3s.

So what changed here is the place where you assign the apple. The reason of code slowing down by placing apple assignment before the if(is_palindrome(t)): is the compiler optimization and cache.

EDIT: see at Dave Bacher answer for the correct answer.

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