Posts

Showing posts with the label python code

Python Code Measure Time

How to measure time of a Python code snippet? We can do it using the timeit module . It has a function called timeit that runs a particular code snippet for N times (one million by default) and gives you the runtime. Today I just used it for a small purpose and thought of writing a note here. >>> from timeit import timeit >>> timeit('"c" >= "a" and "c" <= "z"') 0.06282545300200582 >>> timeit('"c".isalpha()') 0.06563570606522262 Here I compared the performance between two snippets : one uses isalpha() to determine if a (lowercase) character is an alphabet or not, another just compares using operators. There is no noticeable performance difference. Please go through the module doc to get some more ideas of how to use the timeit module , if will often come handy when you quickly want to measure running time of different Python code.

Prime Number Generator in Python using Sieve Method

I have implemented a prime number generator in Python using Sieve of Eratosthenes . Here is my code: import math high = 10000 root = int(math.sqrt(high) + 1.0) ara = [x % 2 for x in xrange(0, high)] ara[1] = 0 ara[2] = 1 x = 3 while x I am looking for ideas to make my code faster. I tested my Python program using the code for solving a problem named Prime Generator in SPOJ . I could solve the problem correctly that took 3 seconds time and 3.8 MB memory. I am posting another code I found here . This one is similar implementation to mine but more Pythonic and much faster: nroot = int(math.sqrt(n)) sieve = [True] * (n+1) sieve[0] = False sieve[1] = False for i in xrange(2, nroot+1): if sieve[i]: m = n/i - i sieve[i*i: n+1:i] = [False] * (m+1) sieve = [i for i in xrange(n+1) if sieve[i]] I updated the above code and now it's 20% faster! :) nroot = int(math.sqrt(n)) sieve = [True] * (n+1) sieve[0] = False sieve[1] = False sieve[4: n+1:2] = [False] * (n / 2 -...