Giter VIP home page Giter VIP logo

simgo's Introduction

SimGo

SimGo is a discrete event simulation framework for Go. It is similar to SimPy and aims to be easy to set up and use.

Processes are defined as simple functions receiving simgo.Process as their first argument. Each process is executed in a separate goroutine, but it is guarantueed that only one process is executed at a time. For examples, look into the examples folder. A short example simulating two clocks ticking in different time intervals looks like this:

package main

import (
    "fmt"

    "github.com/fschuetz04/simgo"
)

func clock(proc simgo.Process, name string, delay float64) {
    for {
        fmt.Println(name, proc.Now())
        proc.Wait(proc.Timeout(delay))
    }
}

func main() {
    sim := simgo.Simulation{}

    sim.ProcessReflect(clock, "slow", 2)
    sim.ProcessReflect(clock, "fast", 1)

    sim.RunUntil(5)
}

When run, the following output is generated:

slow 0
fast 0
fast 1
slow 2
fast 2
fast 3
slow 4
fast 4

You can find more examples in the examples directory.

Copyright and License

Copyright © 2021 Felix Schütz.

Licensed under the MIT License. See the LICENSE file for details.

simgo's People

Contributors

fschuetz04 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

simgo's Issues

Simulation speed issue

I created the bank renege example model respectively with simpy and simgo.

What suprised me is that the run time of both models are quite similar, Python even faster for 10%.

I never used Go before, so wondering what the cause may be. Do you have any idea?

simpy code:

import time
import random

import simpy

RANDOM_SEED = 42
N_COUNTERS = 50
N_CUSTOMERS = 1000000  # Total number of customers
MEAN_ARRIVAL_INTERVAL = 10.0  # Generate new customers roughly every x seconds
PATIENCE = 16
MEAN_TIME_IN_BANK = 12.0


def source(env, number, interval, counter):
    """Source generates customers randomly"""
    for i in range(number):
        c = customer(env, f"Customer{i:02d}", counter, time_in_bank=MEAN_TIME_IN_BANK)
        env.process(c)
        t = random.expovariate(1.0 / interval)
        yield env.timeout(t)


def customer(env, name, counter, time_in_bank):
    """Customer arrives, is served and leaves."""

    with counter.request() as req:
        # Wait for the counter or abort at the end of our tether
        results = yield req | env.timeout(PATIENCE)

        if req in results:
            # We got to the counter
            tib = random.expovariate(1.0 / time_in_bank)
            yield env.timeout(tib)
        # else:
        # We reneged


# Setup and start the simulation
# print("Bank renege")
random.seed(RANDOM_SEED)
env = simpy.Environment()

# Start processes and run
counter = simpy.Resource(env, capacity=N_COUNTERS)
env.process(source(env, N_CUSTOMERS, MEAN_ARRIVAL_INTERVAL, counter))


start_time = time.time()
env.run()
end_time = time.time()
print("Elapsed time:", end_time - start_time)
print(env.now)

Python 3.12.1
output:

Elapsed time: 16.356430292129517

simgo code:

package main

import (
	"fmt"
	"math/rand"
	"time"

	"github.com/fschuetz04/simgo"
)

const (
	RandomSeed          = 42
	NCounters           = 50
	NCustomers          = 1000000
	MeanArrivalInterval = 10
	MaxWaitTime         = 16
	MeanTimeInBank      = 12
)

func customerSource(proc simgo.Process) {
	counters := NewResource(proc, NCounters)

	for id := 1; id <= NCustomers; id++ {
		proc.ProcessReflect(customer, id, counters)
		delay := rand.ExpFloat64() * MeanArrivalInterval
		proc.Wait(proc.Timeout(delay))
	}
}

func customer(proc simgo.Process, id int, counters *Resource) {

	request := counters.Request()
	timeout := proc.Timeout(MaxWaitTime)
	proc.Wait(proc.AnyOf(request, timeout))

	if !request.Triggered() {
		request.Abort()
		return
	}

	delay := rand.ExpFloat64() * MeanTimeInBank
	proc.Wait(proc.Timeout(delay))

	counters.Release()
}

func timeCost() func() {
	start := time.Now()
	return func() {
		tc := time.Since(start)
		fmt.Printf("time cost = %v\n", tc)
	}
}

func runSim(sim *simgo.Simulation) {
	defer timeCost()()
	sim.Run()
	fmt.Printf("%.f\n", sim.Now())
}

func main() {
	rand.Seed(RandomSeed)

	sim := simgo.Simulation{}

	sim.Process(customerSource)

	runSim(&sim)
}

Golang go version go1.22.2 linux/amd64
output:

time cost = 18.406199488s

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.