Java中的离散事件模拟时间单位

时间:2017-01-16 14:07:01

标签: java clock seed

我正在使用Java进行离散事件模拟,代码相关的时间如下;

class Event implements Runnable, Comparable {
    double time;
    Runnable runnable;

    Event(double time, Runnable aRunnable) {
        this.time = time;
        runnable = aRunnable;
    }

    public boolean lessThan(Comparable y) {
        Event e = (Event) y; // Will throw an exception if y is not an Event
        return this.time <= e.time;
    }

    @Override
    public void run() {
        runnable.run();

    }
}

class Simulator extends AbstractSimulator {

    static Random rnd;
    static double time;
    double endTime;


    static double now() {
        return time;
    }

    Simulator(long seed, double simDuration) {
        time = 0.0;
        events = new ListQueue();
        rnd = new Random(seed);
        endTime = simDuration;
    }

    void doAllEvents() {
        Event e;
        while ((e = (Event) events.removeFirst()) != null && time < endTime) {
            if(time > e.time)
                System.out.printf("Something is worng! time=%f eventtime=%f",time,e.time);
            time = e.time;
            e.run();
            System.out.printf("\n Time = %f", time);

        }
    }

我根据事件失败时间考虑结果,但是我需要在绘制时使用单位。

Java用于模拟时间的单位是什么?或者我可以将它们视为第二个?或者有任何计算可以将其转换为现实世界时间吗?

提前致谢,

最诚挚的问候,

更新:

感谢您的回答,我试着测量确切的时间,但我在这里遇到了问题。现有的虚拟仿真时间是测量网络寿命。并且它与一个例子的确切时间不一样;当我为75个设备运行模拟时,netorklifetime更短,比如70.0,但实际时间超过35个设备,寿命为1500.0。发生这种情况是因为每个设备都在重复这些事件。

我需要在这里找到虚拟模拟时间的单位。

再次感谢...

1 个答案:

答案 0 :(得分:0)

您可以使用List<Event> events = new ArrayList<Event>(); ScheduledExecutorService executor = Executors.newScheduledThreadPool(4); for (Event event : events) { executor.schedule(event, (long) event.time, TimeUnit.MILLISECONDS); } try { executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } 来模拟离散事件,例如

Event

有几点可能会有所帮助:

  1. 我认为将池的大小设置为超过您拥有的核心数量(上例中为4)是值得的。
  2. Comparable无需为上面的代码段实施long
  3. 我会将double类型用于时间字段,而不是while
  4. 更新如果您不想使用执行程序或线程,您可以按时间对事件进行排序,并等待使用List<Event> events = new ArrayList<Event>(); events.add(new Event(1000d, () -> System.out.println("event1"))); events.add(new Event(2000d, () -> System.out.println("event2"))); //adding more events ... Collections.sort(events); //Fix start time long start = System.currentTimeMillis(); for (Event event : events) { //Wait until event time is <= than current - start time while (event.time > System.currentTimeMillis() - start); event.run(); } 循环触发事件,如下所示:< / p>

    python -c "import theano; theano.test()"
    
相关问题