Search code examples
pythonoptimizationpremature-optimization

Python | efficiency and performance


Lets say I'm going to save 100 floating point numbers in a list by running a single script, most probably it will take some memory to process.So if this code executes every time as a requirement of an application there will be performance hits, so my question is how to maintain efficiency in order to gain performance.

Mock-up code:

def generate_lglt():
    float1, float2 = 27.2423423, 12.2323245
    lonlats = []
    for val in range(100, 0, -1):
        lonlats.append(random.uniform(float1, float2))
        lonlats.append(random.uniform(float1, float2))
        lonlats.append(random.uniform(float1, float2))
        lonlats.append(random.uniform(float1, float2))
        lonlats.append(random.uniform(float1, float2))
    print lonlats

Thanks.


Solution

  • If generate_lglt() is going to be called a lot of different times, you may want to keep from regenerating the same range(100,0,-1) with every call of the code. You may want to cache that generated range somewhere and use it over and over again.

    Also, if you are going to be exiting a for loop without completing each iteration, use xrange instead of range.