简体   繁体   中英

Why is python being slow? And how can I make it faster?

import numpy as np
import random
import matplotlib.pyplot as plt

 # set grid size, M*N (row, col)
 M: int = 5
 N: int = 5

def moves(pos: tuple, dpos: tuple) -> tuple:
     return (pos[0] + dpos[0], pos[1] + dpos[1])


def check_neighbors(white_pos: tuple, black_pos: tuple) -> bool:
  stationary = white_pos
  up = (white_pos[0], white_pos[1] + 1)
  upper_right = (white_pos[0] + 1, white_pos[1] + 1)
  upper_left = (white_pos[0] - 1, white_pos[1] + 1)
  left = (white_pos[0] - 1, white_pos[1])
  right = (white_pos[0] + 1, white_pos[1])
  lower_left = (white_pos[0] - 1, white_pos[1] - 1)
  down = (white_pos[0], white_pos[1] - 1)
  lower_right = (white_pos[0] + 1, white_pos[1] - 1)

  if (black_pos == stationary) or (black_pos == up) or (black_pos == upper_right) or (black_pos == upper_left) or (black_pos == left) or (black_pos == right) or (black_pos == lower_left) or (black_pos == down) or (black_pos == lower_right):
    return True
else:
    return False
def run_sim():
 w_x0 = random.sample([i for i in range(0,M)], 1)
 w_y0 = random.sample([j for j in range(0,N)], 1)

 b_x0 = random.sample([i for i in range(0,M)], 1)
 b_y0 = random.sample([j for j in range(0,N)], 1)


 white = [(x,y) for x, y in zip(w_x0, w_y0)]
 black = [(x,y) for x, y in zip(b_x0, b_y0)]
 stop: bool = False
 n: int = 0
 t: int = 0
 while stop != True:
    if check_neighbors(white[n], black[n]) == True:
        stop = True
    else:
        dt_w = random.sample([i for i in range(-1,2)], 2)
        dt_bl = random.sample([i for i in range(-1,2)], 2)
        white.append(moves(white[n], dt_w))
        black.append(moves(black[n], dt_bl))
        t = t+1
        n = n+1
 return n

  t_dist = [run_sim() for i in range(100)]
  print(t_dist)

excuse the terrible formatting

when it gets to t_dist = [run_sim() for i in range(100)] it takes FOREVER to run (I mean like wayy over 60 seconds). How can I get it to run faster and get my results? Why is it so computationally expensive?

I am using a jupyter notebook. I also tried just plain running it as a .py file and it is still slow. I tried using the debugger and after setting a breakpoint at t_dist = , it only shows a few iterations and then stops. If I set it to range(5), it works just fine but starts spazzing with bigger numbers (ie 100, 10000), which is what I want to run the simulation as.

If you want to know only the distribution, you should define max_t and please adjust the value.

def check_neighbors(a,b):
    return abs(a[0]-b[0]) + abs(a[1]-b[1]) <= 1 or\
 (abs(a[0]-b[0])==1 and abs(a[1]-b[1])==1)
def moves(a,b):
    return (a[0]+b[0], a[1]+b[1])
def run_sim(M=5, N=5, max_t=10**6):
    w_co = [random.randrange(0,M), random.randrange(0,N)]# to produce random integer, you can use randrange
    b_co = [random.randrange(0,M), random.randrange(0,N)]

    t: int = 0
    while t<max_t:
        if check_neighbors(w_co, b_co) is True: # for bool, `is True` is strict
            break
        else:
            dt_w = [random.randrange(-1,2) for _ in range(2)]
            dt_b = [random.randrange(-1,2) for _ in range(2)]
            w_co=moves(w_co, dt_w)
            b_co=moves(b_co, dt_b)
            t+=1
            if (t%(max_t//20)==0):
                print(f"\t{t}") # check if the program is processing or not
    return t

t_dist = []
for i in range(100):
    if (i%10==1):
        print(i) # check the process
    t_dist.append(run_sim(M=5, N=5, max_t=10**6))
print(t_dist)

Additionally, this is a histogram of exapmle. The graph shows some cases take very, very long time.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM