Python Forum
Optimize a game of life (4 sec for python when 6 ms for C version !)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Optimize a game of life (4 sec for python when 6 ms for C version !)
#1
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()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  run part of a script with a different version of Python jdog 2 444 Jan-09-2024, 08:49 PM
Last Post: jdog
  How to find out from outside Python (in Windows) the current version of Python? pstein 4 730 Oct-04-2023, 10:01 AM
Last Post: snippsat
  How can I multithread to optimize a groupby task: davisc4468 0 707 Jun-30-2023, 02:45 PM
Last Post: davisc4468
  How to resolve version conflicts in Python? taeefnajib 0 908 Apr-27-2023, 08:37 PM
Last Post: taeefnajib
  Python venv and PIP version issue JanOlvegg 2 1,252 Feb-22-2023, 02:22 AM
Last Post: JanOlvegg
  Python Version upgrade nitinkukreja 1 894 Feb-04-2023, 10:27 PM
Last Post: Larz60+
  Can't update new python version on Pycharm GOKUUUU 6 3,793 Jul-23-2022, 09:24 PM
Last Post: GOKUUUU
  do you have an idea to optimize this code[recursion]]? netanelst 4 1,284 May-20-2022, 06:41 PM
Last Post: jefsummers
  Building python (3.9.5) with different libexpat version (2.4.6) raghupcr 0 1,304 Feb-25-2022, 11:29 AM
Last Post: raghupcr
  Python keeps running the old version of the code quest 2 3,748 Jan-20-2022, 07:34 AM
Last Post: ThiefOfTime

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020