4'4 Simulation in C - PowerPoint PPT Presentation

1 / 26
About This Presentation
Title:

4'4 Simulation in C

Description:

Loop until first 'TotalCustomers' have departed. while(NumberOfDepartures TotalCustomers ) ... the vent type(arrival or departure), and the event time-stamp. ... – PowerPoint PPT presentation

Number of Views:22
Avg rating:3.0/5.0
Slides: 27
Provided by: wwwold
Category:

less

Transcript and Presenter's Notes

Title: 4'4 Simulation in C


1
4.4 Simulation in C
  • C is a widely used programming language that
    has been extensively in simulation.
  • The following components are common to almost all
    models written in C
  • Clock
  • A variable defining simulated time.
  • Initialization subroutine
  • A routine to define the system state at time 0
  • Min-time event subroutine
  • A routine that identified the imminent event
    that is, the element of the future event list
    which has the smallest time-stamp

2
4.4 Simulation in C
  • Event subroutines
  • For each event type, a subroutine to update
    system state (and cumulative statistics) when
    that event occurs
  • Random-variate generators
  • Routines to generate samples from desired
    probability distributions
  • Main program
  • Provides overall control of the event-scheduling
    algorithm
  • Report generator
  • A routine that computes summary statistics from
    cumulative statistics and print a report at the
    end of the simulation

3
(No Transcript)
4
4.4 Simulation in C
  • Example 4.2 (Single-Server Queue Simulation in
    C)
  • The grocery checkout counter, defined in detail
    Example 4.1 is simulated using C.

5
4.4 Simulation in C
6
4.4 Simulation in C
  • C Main program for single-server queue
    simulation
  • include ltiostreamgt
  • include ltmath.hgt
  • include ltqueuegt
  • class Event
  • friend bool operatorlt(const Event e1, const
    Event e2)
  • friend bool operator(const Event e1, const
    Event e2)
  • public
  • Event()
  • enum EvtType arrival, departure
  • Event(EvtType type, double etime)
  • _type(type), _etime(etime)

7
4.4 Simulation in C
  • C Main program for single-server queue
    simulation
  • EvtType get_type() return _type
  • double get_time() return _etime
  • protected
  • EvtType _type
  • double _etime
  • bool operator lt(const Event e1, const Event e2)
  • return e2._etime lt e1._etime
  • bool operator (const Event e1, const Event
    e2)
  • if (e1._etime ! e2._etime) return false
  • if (e1._type Eventdeparture) return
    true
  • return false

8
4.4 Simulation in C
  • C Main program for single-server queue
    simulation
  • //global representation
  • double Clock, MeanInterArrivalTime,
    MeanServiceTime, SIGMA, LastEventTime,
  • TotalBusy, MaxQueueLength, SumResponseTime
  • long NumberOfCustomers, QueueLength,
    NumberInService,
  • TotalCustomers, NumberOfDepartures, LongService
  • Priority_queueltEventgt FutureEventList
  • QueueltEventgt Customers
  • main(int argc, char argv)
  • // assign values to input variables
  • MeanInterArrivalTime 4.5

9
4.4 Simulation in C
  • C Main program for single-server queue
    simulation
  • MeanServiceTime 3.2
  • SIGMA 0.6
  • TotalCustomers 1000
  • long seed atoi(argv1)
  • srandom(seed)
  • // Initialize the simulation
  • Initialization()
  • // Loop until first "TotalCustomers" have
    departed
  • while(NumberOfDepartures lt TotalCustomers )

10
4.4 Simulation in C
  • C Main program for single-server queue
    simulation
  • // get the next event, and remove from the event
    list
  • Event evt FutureEventList.top()
  • FutureEventList.pop()
  • Clock evt.get_time()
  • if(evt.get_type() Eventarrival )
    ProcessArrival(evt)
  • else ProcessDeparture(evt)
  • ReportGeneration()

11
4.4 Simulation in C
  • C Main program for single-server queue
    simulation
  • Class Event represents an event. It store a code
    for the vent type(arrival or departure), and the
    event time-stamp.
  • It has associated methods (functions) for
    creating an event and accessing its data.
  • It has also has associated special functions,
    called operators, which provide semantic meaning
    to relational operators lt and between events.
  • The main program routine first gives values to
    variables describing model parameters, and then
    calls routine Initialization to initialize other
    variable such as the statistics-gathering
    variables.

12
4.4 Simulation in C
  • C Initialization routine for single-server
    queue simulation
  • void Initialization()
  • // initialize global variables
  • Clock 0.0
  • QueueLength 0
  • NumberInService 0
  • LastEventTime 0.0
  • TotalBusy 0
  • MaxQueueLength 0
  • SumResponseTime 0.0
  • NumberOfDepartures 0
  • NumNormals 0
  • LongService 0
  • // create first arrival event
  • Event evt(Eventarrival, expon(MeanInterArrivalT
    ime))
  • FutureEventList.push(evt)

13
4.4 Simulation in C
  • C Initialization routine for single-server
    queue simulation
  • The routine Initialization is called to
    initialize the values of global variables, create
    the first arrival event, and schedule it.
  • The event is created by making a local variable
    named evt and having C call the class
    constructor (specifying the event time and
    time-of-occurrance).
  • It is important to note that the scheduling call
    (to method push of the priority_queue class) is
    call-by-value, which means that the local
    variable evt is copied within the call to push.
  • The local variable evt disappears after
    Initialization has completed. Pointers are not
    used in this code. The C Standard Libraries
    work safely with copies of objects.

14
4.4 Simulation in C
  • C arrival event routine for single-server queue
    simulation
  • void ProcessArrival(Event evt)
  • Customers.push(evt) // push arrival
    onto the queue
  • QueueLength // increment
    number waiting
  • // if the server is idle, fetch the event, do
    statistics,
  • // and put into service
  • if( NumberInService 0 )
  • ScheduleDeparture()
  • else
  • // server is busy
  • TotalBusy (Clock - LastEventTime)

15
4.4 Simulation in C
  • C arrival event routine for single-server queue
    simulation
  • // adjust max queue length statistics
  • if( MaxQueueLength lt QueueLength )
  • MaxQueueLength QueueLength
  • // schedule the next arrival
  • Event next_arrival(Eventarrival,
  • Clockexpon(MeanInterArrivalTime))
  • FutureEventList.push(next_arrival)
  • LastEventTime Clock

16
4.4 Simulation in C
  • C arrival event routine for single-server queue
    simulation
  • Routine ProcessArrival starts by pushing a copy
    of the event that triggers it onto a queue, and
    then increments the variable tracking the total
    number of customers in the system.
  • If the arrival shows up to an empty system, then
    ScheduleDeparture is called to put the arrival
    into service, sample its service time, and
    schedule its departure.
  • If the server is busy upon arrival, the length of
    time the server has been busy since the last
    event is computed (by subtracting the time of
    last event from the current time) and added to a
    running total, TotalBusy.
  • Next the current queue length is tested against
    the largest previous queue length, with that max
    statistic being updated if exceeded.
  • The last step of the arrival routine is to
    schedule the next arrival, in much the same
    fashion as the initial arrival event was
    scheduled.
  • The arrival time is computed as the sum of the
    current simulation time with an exponentially
    distributed increment.

17
4.4 Simulation in C
  • C departure event routine for single-server
    queue simulation
  • void ProcessDeparture(Event evt)
  • // get the customer description
  • Event finished Customers.front()
  • Customers.pop()
  • // if there are customers in queue then schedule
  • // the departure of the next one
  • if( QueueLength ) ScheduleDeparture()
  • else NumberInService 0
  • // measure the response time and add to the sum
  • double response (Clock - finished.get_time())
  • SumResponseTime response
  • if( response gt 4.0 ) LongService //
    record long service
  • TotalBusy (Clock - LastEventTime) // we
    were busy

18
4.4 Simulation in C
  • C departure event routine for single-server
    queue simulation
  • NumberOfDepartures // one
    more gone
  • LastEventTime Clock
  • void ScheduleDeparture()
  • double ServiceTime
  • // get the job at the head of the queue
  • while( (ServiceTime normal(MeanServiceTime,
    SIGMA)) lt 0 )
  • Event depart Event(Eventdeparture,
    ClockServiceTime)
  • FutureEventList.push(depart)
  • NumberInService 1
  • QueueLength-- // the one going into
    service isn't waiting

19
4.4 Simulation in C
  • C departure event routine for single-server
    queue simulation
  • Routine ProcessDeparture executes the event
    associated with a job leaving service.
  • Data structure Customers is a queue from the C
    Standard Library, used to enqueue the customers
    in their order of arrival.
  • Since the queue is first-come-first-serve, the
    event (i.e. customer) at the front of the queue
    is the one which is departing.
  • A call to method front returns a copy of the
    event at the front of the queue, and a call to
    method pop removes it from the queue altogether.
  • Next, if there are any jobs waiting for service,
    the next one has its departure scheduled by
    making a call to ScheduleDeparture.
  • Next the response time is computed as the
    difference between the job's time-of-arrival and
    time-of-departure.

20
4.4 Simulation in C
  • C departure event routine for single-server
    queue simulation
  • The former value is simply the time-stamp on the
    event pulled from the front of the queue, and the
    latter is the current time.
  • The sampled response time is added to the running
    total of all such (for the purpose of computing
    an average response time later), and if the
    response time exceeds 4 the variable counting the
    number of "long" jobs is incremented.
  • Finally, the total busy time variable is updated
    and the number of departures (a variable which
    affects the main loop termination) is
    incremented.

21
4.4 Simulation in C
  • C report generator for single-server queue
    simulation
  • void ReportGeneration()
  • double RHO TotalBusy/Clock
  • double AVGR SumResponseTime/TotalCustomers
  • double PC4 ((double)LongService)/TotalCustomer
    s
  • cout ltlt "SINGLE SERVER QUEUE SIMULATION - GROCERY
    STORE CHECKOUT COUNTER \n"
  • ltlt endl
  • cout ltlt "\tMEAN INTERARRIVAL TIME
    "
  • ltlt MeanInterArrivalTime ltlt endl
  • cout ltlt "\tMEAN SERVICE TIME
    "
  • ltlt MeanServiceTime ltlt endl
  • cout ltlt "\tSTANDARD DEVIATION OF SERVICE TIMES
    "
  • ltlt SIGMA ltlt endl
  • cout ltlt "\tNUMBER OF CUSTOMERS SERVED
    "
  • ltlt TotalCustomers ltlt endl ltlt endl

22
4.4 Simulation in C
  • C report generator for single-server queue
    simulation
  • cout ltlt "\tSERVER UTILIZATION
    "
  • ltlt RHO ltlt endl
  • cout ltlt "\tMAXIMUM LINE LENGTH
    "
  • ltlt MaxQueueLength ltlt endl
  • cout ltlt "\tAVERAGE RESPONSE TIME
    "
  • ltlt AVGR ltlt " MINUTES" ltlt endl
  • cout ltlt "\tPROPORTION WHO SPEND FOUR \n"
  • ltlt "\t MINUTES OR MORE IN SYSTEM
    "
  • ltlt PC4 ltlt endl
  • cout ltlt "\tSIMULATION RUNLENGTH
    "
  • ltlt Clock ltlt " MINUTES " ltlt endl
  • cout ltlt "\tNUMBER OF DEPARTURES
    "
  • ltlt TotalCustomers ltlt endl

23
4.4 Simulation in C
  • Random-variate generators for single-server queue
    simulation
  • double unif()
  • define RANGE 0x7fffffff
  • return (random()/(double)RANGE)
  • double expon(double mean)
  • return -meanlog( unif() )

24
4.4 Simulation in C
  • Random-variate generators for single-server queue
    simulation
  • double normal(double mean, double sigma)
  • define PI 3.1415927
  • double ReturnNormal
  • // should we generate two normals?
  • if(NumNormals 0 )
  • double r1 unif()
  • double r2 unif()
  • ReturnNormal sqrt(-2log(r1))cos(2PIr2)
  • SaveNormal sqrt(-2log(r1))sin(2PIr2)
  • NumNormals 1
  • else
  • NumNormals 0
  • ReturnNormal SaveNormal
  • return ReturnNormalsigma mean

25
4.4 Simulation in C
  • Random-variate generators for single-server queue
    simulation
  • For the sake of convenience, the code uses the C
    library's random() function to generate the
    random number stream.
  • Better RNGs are generally available and ought to
    be used in real contexts. random() will not
    return value 0, so function unif() will not
    return value zero, and thus it is safe to take
    the natural logarithm of unif() when transforming
    a uniform sample into an exponential sample
    (using the standard inverse CDF transform
    technique one uses with exponentials).
  • Function normal() uses the Box-Mueller
    transformation. This algorithm accepts two
    independent uniform random numbers as input and
    produces two independent (0,1) normal random
    variables as a result.

26
4.4 Simulation in C
  • Random-variate generators for single-server queue
    simulation
  • Thus our implementation saves one of the two
    generated normals to be used on the next call.
    However the (0,1) normal is obtained, it is
    transformed into a normal with specified mean and
    deviation through the standard linear
    transformation.
Write a Comment
User Comments (0)
About PowerShow.com