Python Forum

Full Version: Optimize a game of life (4 sec for python when 6 ms for C version !)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I'm trying to optimize my game of life in Python but it takes 2 to 4 sec for one life cycle (without display) when it takes 6 ms with the version in C. The difference is so big between the 2 langages and I am sure something is wrong in my python version. Maybe the multiple accesses to a mumpy matrice is too time cosuming so I should use something else with faster read access ?
Do you have an idea to optimize part of my code ?
For your information, it first reads a json file that read a grill of about 800/800 to initialize the first state of the environment.

Thanks for your help !

Fabrice

#!/usr/bin/python3

import pygame
import json
import sys
import numpy
import time

mat=""
outputmat=""
switchmat=""
conf=""
screen=""

def load_conf():
  try:
    with open('conf.json') as json_conf:
      data = json.load(json_conf)
      return data
  except:
    print("Le fichier conf.json n'existe pas.")
    sys.exit(1)

def init_pygame():
  global conf
  pygame.init()

  size = width, height = conf["width"], conf["height"]
  screen1 = pygame.display.set_mode(size)
  pygame.display.set_caption(conf["title"])
  return screen1

def init_game_of_life_mat():
  global conf
  mmat = numpy.zeros(shape=(conf["number_cellulars_y"], conf["number_cellulars_x"]), dtype=bool)
  for point in conf["cellulars"] :
    mmat[point["y"]][point["x"]] = 1
  return mmat

def draw_game_of_life_cellular(x, y, size_x, size_y, color):
  global screen
  for index_x in range(x * size_x, (x * size_x) + size_x):
    for index_y in range(y * size_y, (y * size_y) + size_y):
      screen.set_at((index_x, index_y), color)

def draw_game_of_life():
  global outputmat, switchmat, conf, screen
  size_x = int(conf["width"] / conf["number_cellulars_x"])
  size_y = int(conf["height"] / conf["number_cellulars_y"])
  screen.fill((0,0,0))
  for y in range(0, len(outputmat)):
    for x in range(0, len(outputmat[y])):
      if outputmat[y][x]:
        draw_game_of_life_cellular(x, y, size_x, size_y, (255, 255, 255))

def quit_event():
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      return True
  return False

def rules_game_of_life(x, y, size_x, size_y):
  global mat
  count = 0
  if mat[y - 1 if y - 1 > -1 else size_y - 1][x - 1 if x - 1 > -1 else size_x - 1]:
    count = count + 1
  if mat[y - 1 if y - 1 > -1 else size_y - 1][x]:
    count = count + 1
  if mat[y][x - 1 if x - 1 > -1 else size_x - 1]:
    count = count + 1
  if mat[y + 1 if y + 1 < size_y else 0][x + 1 if x + 1 < size_x else 0]:
    count = count + 1
  if mat[y + 1 if y + 1 < size_y else 0][x]:
    count = count + 1
  if mat[y][x + 1 if x + 1 < size_x else 0]:
    count = count + 1
  if mat[y + 1 if y + 1 < size_y else 0][x - 1 if x - 1 > -1 else size_x - 1]:
    count = count + 1
  if mat[y - 1 if y - 1 > -1 else size_y - 1][x + 1 if x + 1 < size_x else 0]:
    count = count + 1

  if mat[y][x]:
    if count == 2 or count == 3:
      return True
    else:
      return False
  else:
    if count == 3:
      return True
    else:
      return False

def compute_game_of_life(size_x, size_y):
  global mat, outputmat
  for y in range(0, len(mat)):
    for x in range(0, len(mat[y])):
      outputmat[y][x] = rules_game_of_life(x, y, size_x, size_y)

def init():
  global conf, screen, mat, outputmat, switchmat
  conf=load_conf()
  print(conf["width"])
  screen = init_pygame()
  mat = init_game_of_life_mat()
  outputmat = init_game_of_life_mat()
  switchmat= init_game_of_life_mat()

def main_loop():
  global mat, outputmat, switchmat
  exit_loop = False
  while not exit_loop:
    exit_loop = quit_event()
    draw_game_of_life()
    t1 = time.process_time()
    switchmat = outputmat
    outputmat = mat
    mat = switchmat
    compute_game_of_life(conf["number_cellulars_x"], conf["number_cellulars_y"])
    t2 = time.process_time()
    print("Time =", (t2 - t1)*1000.0 , " ms")
    pygame.display.flip()

def main():
  init()
  main_loop()

main()