Fix speed

speed

Based on a recent discussion about teaching programming and if speed of execution matters I wrote this snippet.

examples/fix-speed/calculate.py

import sys

def run(X, Y):
    total = 0
    for x in range(X):
        for y in range(Y):
            width, height = read_config()
            total += x*width + y*height
    print(total)

def read_config():
    import csv
    with open('config.csv', newline='') as fh:
        reader = csv.DictReader(fh)
        for row in reader:
            return int(row['width']), int(row['height'])


if __name__ == "__main__":
    if len(sys.argv) != 3:
        exit("Usage: {sys.argv[0]} X Y")
    X = int(sys.argv[1])
    Y = int(sys.argv[2])
    run(X, Y)

Can you suggest how to improve the speed of this code?

In order to try it create a file called config.csv with this content

examples/fix-speed/config.csv

width,height
23,19

and then run

time python3 calculate.py 1000 500

On my computer this takes 5 seconds to run.

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Python Maven web site.

Gabor Szabo