De-Sim的最后一个示例展示了De-Sim的性能,事件的执行速度达到了每秒10000+
示例代码如下
import time
import de_sim
class InitMsg(de_sim.EventMessage):
'An InitMsg message'
def obj_name(i):
return f'sim_obj_{i}'
class CyclicalMessagesSimulationObject(de_sim.SimulationObject):
""" Send events around a cycle of objects """
def __init__(self, name, obj_num, cycle_size):
super().__init__(name)
self.obj_num = obj_num
self.cycle_size = cycle_size
def next_obj(self):
next = (self.obj_num + 1) % self.cycle_size
return self.simulator.simulation_objects[obj_name(next)]
def send_next_event(self):
# send event to next CyclicalMessagesSimulationObject
self.send_event(1, self.next_obj(), InitMsg())
def init_before_run(self):
self.send_next_event()
def handle_event(self, event):
self.send_next_event()
event_handlers = [(InitMsg, 'handle_event')]
# register the message types sent
messages_sent = (InitMsg, )
def make_cyclical_messaging_network_sim(simulator, num_objs):
# make a simulation with cyclical messaging network
sim_objects = [CyclicalMessagesSimulationObject(obj_name(i), i, num_objs)
for i in range(num_objs)]
simulator.add_objects(sim_objects)
def prep_simulation(simulator, num_sim_objs):
simulator.reset()
make_cyclical_messaging_network_sim(simulator, num_sim_objs)
simulator.initialize()
def test_performance():
simulator = de_sim.Simulator()
end_sim_time = 100
num_sim_objs = 4
max_num_profile_objects = 300
max_num_sim_objs = 5000
print()
print(f"Performance test of cyclical messaging network: "
f"end simulation time: {end_sim_time}")
unprofiled_perf = ["\n#sim. obs\t# events\trun-time (s)\tevents/s".expandtabs(14)]
while num_sim_objs < max_num_sim_objs:
# measure execution time
prep_simulation(simulator, num_sim_objs)
start_time = time.process_time()
num_events = simulator.simulate(end_sim_time).num_events
run_time = time.process_time() - start_time
unprofiled_perf.append(f"{num_sim_objs:>9}\t{num_events:>7}\t"
f"{run_time:11.3f}\t{num_events / run_time:8.0f}".expandtabs(14))
num_sim_objs *= 4
print("\n".join(unprofiled_perf))
test_performance()