De-Sim示例分析(六)De-Sim性能

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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值