Skip to content

Instantly share code, notes, and snippets.

@RodrigoPrior
Last active October 24, 2016 21:44
Show Gist options
  • Save RodrigoPrior/9f7b28f3c2bc038810ceab5b71de0229 to your computer and use it in GitHub Desktop.
Save RodrigoPrior/9f7b28f3c2bc038810ceab5b71de0229 to your computer and use it in GitHub Desktop.
python multiprocessing
import time
import random
import numpy as np
import multiprocessing as mp
class simulacron(object):
"""sync and async functs for simulacron."""
def __init__(self, n=512*5, freq=512, freq2=4):
super(simulacron, self).__init__()
self.n = n # numb of cycles
self.freq = freq # Hz
self.freq2 = freq2 # Hz
self.stimout = 0
def sync_signal(self):
'''timed sync signal'''
i = 0
while i < self.n:
yield random.random()
time.sleep(1/self.freq)
i += 1
def async_stim(self):
'''
async function.
return: random type of stim 0..2
'''
i = 0
while True:
self.stimout[:] = i, random.choice([0, 1, 2])
time.sleep(1/self.freq2)
i += 1
if __name__ == '__main__':
s = simulacron()
s.stimout = mp.Array('i', range(2)) # 'd' for float
proc = mp.Process(target=s.async_stim)
proc.start()
a = []
for i in s.sync_signal():
# print(s.stimout[:]+[i,])
a.append(s.stimout[:]+[i, ])
proc.terminate()
# stats: sum of frames in each cycle
# should be equal to self.freq/self.freq2
n = np.array(a)
for i in np.unique(n[:, 0]):
print('Frames in async_stim', i, '->', np.sum(n[:, 0] == i))
print('Expected:', s.freq/s.freq2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment