main(){ sim_init(); while (narr < TOTAL_EVENTS){ switch (act()){ case ARRIVAL: arrival(); break; case DEPARTURE: departure(); break; default: printf("error in act procedure\n"); exit(1); break; } /* end switch */ } /* end while */ printf("Probablity a packet is blocked: \nbatch arrival: %8.4f \nsingle packet arrival: %8.4f\n", ((float) batch_nloss) / batch_packets, ((float) nloss) / (total_packets - batch_packets)); return(0); } /* end main */
float run() { int i; while (narr < total_events) { switch (act()) { case ARRIVAL: arrival(); break; case DEPARTURE: departure(); break; default: printf("error in act procedure\n"); exit(1); break; } /* end switch */ } /* end while */ /* printf("The mean queue length seen by arriving customers is: %8.4f\n", ((float) q_sum) / narr); printf("Probablity a packet is blocked is: %8.4f\n", ((float) nloss) / narr); */ fprintf (stderr, "%.6f\n", ((float) nloss) / narr); return ((float) nloss) / narr; } /* end main */
void SpikeQueue::enqueue(nidx_t source, delay_t delay, delay_t elapsed) { unsigned index = slot(delay-elapsed); if(index < 0 || index >= m_queue.size()) throw std::runtime_error("SpikeQueue index out of bounds."); m_queue.at(index).push_back(arrival(source, delay)); }
/******************************************************************* void runSimulationA(Simulation sim, int iTimeLimit) Purpose: Runs a simulation on the event list. Prints a table displaying the arrival and departures of travelers Parameters: I Simulation simulation I int iTimeLimit Returns: 1. Does not return anything functionally Notes: 1. Uses removeLL function *******************************************************************/ void runSimulationA(Simulation sim, int iTimeLimit) { Event event; // Creates a local event variable to store current // nodes event information into (uses in simulation evaluation) Server server1 = newServer("Server 1"); // Creates a new server - // - contains Server Name, whether it is busy or not, and a widget Server server2 = newServer("Server 2"); // creates the second server for our program (refer to server1 comments) Queue queue1 = newQueue("Queue 1"); // Creates a new queue Queue queue2 = newQueue("Queue 2"); // Creates a new queue if (sim->bVerbose == TRUE) printf("%-4s %-6s %-10s\n", "TIME", "WIDGET", "EVENT"); //table header while (removeLL(sim->eventList, &event)) { // buffer to stop arrivals after the time limit if (event.iEventType == EVT_ARRIVAL && event.iTime > iTimeLimit) continue; sim->iClock = event.iTime; // advance clock to current event time // the switch evaluates the eventType switch(event.iEventType) { case EVT_ARRIVAL: arrival(sim, &event.widget); queueUp(sim, queue1, &event.widget); seize(sim, queue1, server1); break; case EVT_SERVER1_COMPLETE: release(sim, queue1, server1, &event.widget); queueUp(sim, queue2, &event.widget); seize(sim, queue2, server2); break; case EVT_SERVER2_COMPLETE: release(sim, queue2, server2, &event.widget); leaveSystem(sim, event.widget); break; default: ErrExit(ERR_ALGORITHM, "Unknown event type: %d\n", event.iEventType); } } // prints the averages produced by the simulation printStatistics(sim, queue1, queue2); // frees servers and queues used in simulation A free(server1); free(server2); free(queue1); free(queue2); }
QString JourneyInfo::arrivalText( bool /*htmlFormatted*/, bool displayTimeBold, bool showRemainingMinutes, bool showDepartureTime, int linesPerRow ) const { QString sTime, sArrival = arrival().toString( "hh:mm" ); if ( displayTimeBold ) { sArrival = sArrival.prepend( "<span style='font-weight:bold;'>" ).append( "</span>" ); } if ( arrival().date() != QDate::currentDate() ) { sArrival += ", " + DepartureInfo::formatDateFancyFuture( arrival().date() ); } if ( showDepartureTime && showRemainingMinutes ) { QString sText = durationToDepartureString( true ); sText = sText.replace( QRegExp( "\\+(?:\\s*| )(\\d+)" ), QString( "<span style='color:%1;'>+ \\1</span>" ) .arg( Global::textColorDelayed().name() ) ); if ( linesPerRow > 1 ) { sTime = QString( "%1<br>(%2)" ).arg( sArrival ).arg( sText ); } else { sTime = QString( "%1 (%2)" ).arg( sArrival ).arg( sText ); } } else if ( showDepartureTime ) { sTime = sArrival; } else if ( showRemainingMinutes ) { sTime = durationToDepartureString( true ); sTime = sTime.replace( QRegExp( "\\+(?:\\s*| )(\\d+)" ), QString( "<span style='color:%1;'>+ \\1</span>" ) .arg( Global::textColorDelayed().name() ) ); } else { sTime.clear(); } return sTime; }
// Given the actor, return a desired velocity in world coordinates // If the actor is the leader, move towards the target; otherwise, // follow the leader without bunching together vec3 Leader::CalculateDesiredVelocity(Actor& actor) { Arrival arrival(m_pTarget); if (actor.agentID == 0) // actor is the leader { return arrival.CalculateDesiredVelocity(actor); } else { Separation separation(m_pTarget, m_pAgents); return 0.7 * separation.CalculateDesiredVelocity(actor) + 0.3 * arrival.CalculateDesiredVelocity(actor); } }
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool Origin::updateChild(Object* child) { Comment* commentChild = Comment::Cast(child); if ( commentChild != NULL ) { Comment* commentElement = comment(commentChild->index()); if ( commentElement != NULL ) { *commentElement = *commentChild; return true; } return false; } // Do not know how to fetch child of type CompositeTime without an index Arrival* arrivalChild = Arrival::Cast(child); if ( arrivalChild != NULL ) { Arrival* arrivalElement = arrival(arrivalChild->index()); if ( arrivalElement != NULL ) { *arrivalElement = *arrivalChild; return true; } return false; } StationMagnitude* stationMagnitudeChild = StationMagnitude::Cast(child); if ( stationMagnitudeChild != NULL ) { StationMagnitude* stationMagnitudeElement = StationMagnitude::Cast(PublicObject::Find(stationMagnitudeChild->publicID())); if ( stationMagnitudeElement && stationMagnitudeElement->parent() == this ) { *stationMagnitudeElement = *stationMagnitudeChild; return true; } return false; } Magnitude* magnitudeChild = Magnitude::Cast(child); if ( magnitudeChild != NULL ) { Magnitude* magnitudeElement = Magnitude::Cast(PublicObject::Find(magnitudeChild->publicID())); if ( magnitudeElement && magnitudeElement->parent() == this ) { *magnitudeElement = *magnitudeChild; return true; } return false; } return false; }
main() { int numcust=0; // Number of customers int time; int i; Item *head; // Head of linked list Item *tail; // Tail of linked list Item *newitem; // Pointer to a new item in linked list Item *curritem; // Current item // Initialize srand48(3); // Seed the pseudorandom number generator head = NULL; tail = NULL; // Generate the new customers and store them in a // linked list for (time=0; time<MAXTIME; time++) { if (arrival(ARRIVALRATE) == 1) { // Load arrival time and service time for new customer newitem = (Item *)malloc(sizeof(Item)); newitem->atime = time; // Arrival time is current time newitem->stime = service(); newitem->next = NULL; // Update the head of the list if it is empty if (numcust==0) { head = newitem; tail = newitem; } else { // Update the tail of the queue tail->next = newitem; tail = newitem; } // Update the number of customers numcust++; } } // Print out the times printf("%d\n",numcust); curritem = head; for (i=0; i<numcust; i++) { printf("%d %d\n",curritem->atime, curritem->stime); free(curritem); // free space of customer already displayed curritem=curritem->next; } }
int main() { int i; initialize(); for (i=0; i<NUM_MAX_EVENTS; i++) { timing(); statistics(); switch(next_event_type) { case 0: arrival(); break; case 1: departure(); break; } } printf("The expected number of customer is queue is %f \n", area_num_in_q/sim_time); return 0; }
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool Origin::removeArrival(const ArrivalIndex& i) { Arrival* object = arrival(i); if ( object == NULL ) return false; return remove(object); }
/**************************** runSimulation ************************************ void runSimulation(Simulation sim, int iTimeLimit) Purpose: Goes through a list of events in a Simulation and run them as they are encountered. Parameters: I Simulation sim The simulation variable containing the list of events. I int iTimeLimit A time limit upon which the simulation will terminate if it is reached before all of the events are ran. Returns: Notes: *******************************************************************************/ void runSimulation(Simulation sim, int iTimeLimit) { //Variables Event event; Server server1, server2; Queue queue1, queue2; //create servers and queues server1 = newServer("Server 1"); queue1 = newQueue("Queue 1"); if (sim->cRunType == 'A') { server2 = newServer("Server 2"); queue2 = newQueue("Queue 2"); } //begin simulation printHeader(sim); while (removeLL(sim->eventList, &event)) { if (event.iTime > iTimeLimit) { printFooter(sim, queue1, queue2); freeServersAndQueues(sim, server1, server2, queue1, queue2); ErrExit(ERR_BAD_INPUT, "Event time (%d) is out of simulation bounds (%d)\n", event.iTime, iTimeLimit); } sim->iClock = event.iTime; switch (event.iEventType) { case EVT_ARRIVAL: arrival(sim, &event.widget); queueUp(sim, &event.widget, queue1); seize(sim, queue1, server1); break; case EVT_SERVER1_COMPLETE: release(sim, queue1, server1); if (sim->cRunType == 'A') //Alternative A follows up with server 2 { queueUp(sim, &event.widget, queue2); seize(sim, queue2, server2); } else //Alternative B and Current leave after server 1 { leaveSystem(sim, &event.widget); } break; case EVT_SERVER2_COMPLETE: release(sim, queue2, server2); leaveSystem(sim, &event.widget); break; default: ErrExit(ERR_ALGORITHM, "Unknown event type: %d\n", event.iEventType); } } printFooter(sim, queue1, queue2); freeServersAndQueues(sim, server1, server2, queue1, queue2); }
// Boilerplate program options code from http://www.radmangames.com/programming/how-to-use-boost-program_options int main(int argc, char** argv) { bool enable_sorting = true; double seed = 0; double power_mean = 300.0; // Watts double power_stdev = power_mean/10.0; double power_estimate_error_stdev = power_stdev/10.0; double arrival_rate = 1000.0; // Jobs per second double completion_time_mean = 0.9*NUM_SERVERS/arrival_rate; // Seconds double completion_time_stdev = completion_time_mean/10.0; double sorting_time_min = completion_time_mean/1000.0; double sorting_time_max = sorting_time_min*2.0; double routing_time_min = sorting_time_min; double routing_time_max = sorting_time_max; try { /** Define and parse the program options */ namespace po = boost::program_options; po::options_description desc("Options"); desc.add_options() ("help", "Print help messages") ("seed", po::value<double>(&seed), "Seed for random number generator") ("power_estimate_error_stdev", po::value<double>(&power_estimate_error_stdev), "Power estimate standard deviation") ("completion_time_stdev", po::value<double>(&completion_time_stdev), "Completion time standard deviation") ("enable_sorting", po::value<bool>(&enable_sorting), "Enable sorting") ; po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); // can throw /** --help option */ if ( vm.count("help") ) { std::cout << "Basic Command Line Parameter App" << std::endl << desc << std::endl; return SUCCESS; } po::notify(vm); // throws on error, so do after help in case // there are any problems } catch(po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl << std::endl; std::cerr << desc << std::endl; return ERROR_IN_COMMAND_LINE; } // BEGIN APPLICATION CODE // DataCenterRandomPtr rand(new DataCenterRandom( seed, power_mean, power_stdev, arrival_rate, completion_time_mean, completion_time_stdev, sorting_time_min, sorting_time_max, routing_time_min, routing_time_max, power_estimate_error_stdev)); PriorityTypePtr sortOrder(new JobEvent::PriorityType(JobEvent::TIME)); PriorityQueueEventListPtr eventList(new PriorityQueueEventList( EVENT_LIST_LEN, sortOrder)); PriorityQueueWorkingServers::SortingDomain sortingDomain; if(enable_sorting){ sortingDomain = PriorityQueueWorkingServers::POWER_AWARE; } else{ sortingDomain = PriorityQueueWorkingServers::RANDOM; } std::ostringstream s; s << seed; AccumulatorStatistics statistics(s.str()); PriorityQueueWorkingServersPtr workingServersQueue(new PriorityQueueWorkingServers( NUM_SERVERS, rand, eventList, statistics.getAccumulator(AccumulatorStatistics::LATENCY), statistics.getAccumulator(AccumulatorStatistics::TOTAL_ENERGY), sortOrder, s.str() + "server_currents.csv", sortingDomain)); PriorityQueueJobSorterPtr sortedJobQueue(new PriorityQueueJobSorter( SORTED_JOBS_LIST_LEN, rand, workingServersQueue, eventList, sortOrder, enable_sorting)); QueueJobBufferPtr unsortedJobQueue(new QueueJobBuffer( UNSORTED_JOBS_LIST_LEN, statistics.getAccumulator(AccumulatorStatistics::TIME_BETWEEN_REJECTED_JOBS), sortedJobQueue)); #ifndef UNITTEST double time = 0; JobEventPtr arrival(new JobEvent(0, Event::JOB_ARRIVAL, sortOrder)); _NOTEL(0,"Welcome to the data center stacked server simulator."); _LOGL(1,"Initialization parameters: "); _LOGL(1,"Sorting enabled: " << enable_sorting); _LOGL(1,"Simulation time: " << MAX_TIME); _LOGL(1,"Event list length: " << EVENT_LIST_LEN); _LOGL(1,"Unsorted jobs list length: " << UNSORTED_JOBS_LIST_LEN); _LOGL(1,"Sorted jobs list length: " << SORTED_JOBS_LIST_LEN); _LOGL(1,"Number of servers: " << NUM_SERVERS); _LOGL(1, *rand); // Queue up initial arrival. _NOTEL(2,"Creating initial arrival event."); eventList->enqueue(arrival); while(time < MAX_TIME){ EventPtr e = eventList->dequeue(); time = e->time; _NOTEL(2, time); if(e->type == Event::JOB_ARRIVAL || e->type == Event::JOB_FINISHED){ JobEventPtr job = boost::static_pointer_cast<JobEvent>(e); if(job->type == Event::JOB_ARRIVAL){ double t = time + rand->sample_arrivalTime(); _NOTEL(2,"Processing job arrival event. Scheduling next job arrival for time " << t); JobEventPtr nextJob(new JobEvent(t, Event::JOB_ARRIVAL, sortOrder)); eventList->enqueue(nextJob); if(!unsortedJobQueue->enqueue(job)){ if(!sortedJobQueue->enqueue(job,time)){ workingServersQueue->enqueue(job,time); } } } else{ // if(job->type == Event::JOB_FINISHED){ _NOTEL(2,"Processing job removal event."); workingServersQueue->remove(job,time); if(enable_sorting){ if(!sortedJobQueue->is_busy() && !sortedJobQueue->is_empty()){ JobEventPtr job = sortedJobQueue->dequeueJob(); workingServersQueue->enqueue(job,time); } } else{ if(!unsortedJobQueue->is_empty()){ JobEventPtr job = unsortedJobQueue->dequeue(); workingServersQueue->enqueue(job,time); } } } } else if(e->type == Event::SORTED_QUEUE_READY){ if(enable_sorting){ _NOTEL(2,"Processing sorted queue ready event."); sortedJobQueue->reset_busy(); if(!sortedJobQueue->is_empty() && !workingServersQueue->is_busy() && !workingServersQueue->is_full()){ JobEventPtr job = sortedJobQueue->dequeueJob(); workingServersQueue->enqueue(job,time); } if(!unsortedJobQueue->is_empty()){ JobEventPtr job = unsortedJobQueue->dequeue(); if(!sortedJobQueue->enqueue(job,time)){ workingServersQueue->enqueue(job,time); } } else{ _NOTEL(2,"Nothing for sorted queue to do."); } } else{ _NOTEL(0,"PROBLEM!!!"); } } else{ // if(e->type == Event::WORKING_SERVERS_QUEUE_READY){ _NOTEL(2,"Processing working servers queue ready event."); workingServersQueue->reset_busy(); if(enable_sorting){ if(!sortedJobQueue->is_busy() && !sortedJobQueue->is_empty()){ JobEventPtr job = sortedJobQueue->dequeueJob(); workingServersQueue->enqueue(job,time); } } else{ if(!unsortedJobQueue->is_empty()){ JobEventPtr job = unsortedJobQueue->dequeue(); workingServersQueue->enqueue(job,time); } } } //_NOTE(3, (*eventList) << std::endl); } _NOTEL(1,"Finished simulation of " << time << " virtual seconds."); _LOGL(0,"Simulation results: " << std::endl << statistics); AccumulatorPtr latency = statistics.getAccumulator(AccumulatorStatistics::LATENCY); AccumulatorPtr total_energy = statistics.getAccumulator(AccumulatorStatistics::TOTAL_ENERGY); _LOGL(0, latency->getMean() << "$\\pm$" << latency->getCI(0.95) << " & " << total_energy->getMean() << "$\\pm$" << total_energy->getCI(0.95)); return 0; // Run the Unit tests #else _NOTEL(0,"Welcome to the unit tests."); test_accumulator(rand,statistics); test_working_servers(workingServersQueue,sortOrder,statistics); return 0; #endif // END APPLICATION CODE // } catch(std::exception& e) { std::cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << std::endl; return ERROR_UNHANDLED_EXCEPTION; } return SUCCESS; } // main
int main(int argc, char **argv){ char *infilename = "mm1.in"; char *outfilename = "mm1.out"; //Read Exec options (実行オプションの読み込み) int option; while( (option = getopt(argc, argv,"i:o:th"))!=-1 ){ switch(option){ case 'i': infilename = optarg; break; case 'o': outfilename = optarg; break; case 't': limit_time_mode = true; break; case 'h': default: usage(argv[0]); return 0; break; } } /*Open input and output file(入力ファイルと出力ファイルを開く)*/ infile = fopen(infilename,"r"); outfile = fopen(outfilename,"w"); /*Specify the number of events for the timing function(イベント数を定義)*/ //Customer Number Limit Mode if(!limit_time_mode) num_events = 2;//到着(Arrival Event)と出発(Departure Event) //Time Limit Mode else num_events = 3;//到着(Arrival Event)と出発(Departure Event)と終了(Simulation End Event) /*Read input parameter.(パラメータの読み込み)*/ if(!limit_time_mode) {//Customer Number Limit Mode fscanf(infile,"%f %f %d",&mean_interarrival,&mean_service,&num_deleyed_required); printf("input %f %f %d\n",mean_interarrival,mean_service,num_deleyed_required); }else{//Time Limit Mode fscanf(infile,"%f %f %f",&mean_interarrival,&mean_service,&time_end); printf("input %f %f %f\n",mean_interarrival,mean_service,time_end); } if(!limit_time_mode) printf("Exec Limit Costomer Number Mode\n"); else printf("Exec Limit Time Mode\n"); /*Write Report heading and input parameter.(入力されたパラメータを書き出し)*/ fprintf(outfile,"Single-server queueing system \n"); fprintf(outfile,"Mean interarrival time Limit %11.3f minutes \n",mean_interarrival); fprintf(outfile,"Mean service time Limit %16.3f minutes \n",mean_service); if(!limit_time_mode) fprintf(outfile,"Number of customers %14d \n",num_deleyed_required); else fprintf(outfile,"Length of the Simulation %9.3f minute \n",time_end); printf("mean interarrival %f \n",mean_interarrival); printf("mean service %f \n",mean_service); /*Initialize the simulation.(シミュレーションの初期化)*/ initialize(); bool sim_run=true; //int arrival_id=0,dep_id=0; while(sim_run){ /*Determine the next event.(次のイベントを定義)*/ timing(); /*Update time-average statistical accumulators(のべ時間の更新)*/ update_time_avg_status(); /*Invoke the appropriate event function.(イベントの実行)*/ switch(next_event_type){ case 1: arrival_id++; printf("[%10.3f] Customer %d is Arrival\n",sim_clock,arrival_id); arrival();//Arrival Event(到着イベント) break; case 2: dep_id++; printf("[%10.3f] Customer %d is Departure\n",sim_clock,dep_id); depart();//Departure Event(出発イベント) break; case 3://for Limit Time Mode /*Invoke the report generator and end the simulation.(レポートを出力してシミュレーションを修了)*/ report(); break; } if(!limit_time_mode){//Limit Customer Number Mode /*Quit the simulation when more delays are not needed.(もう客が来なくてもいいならシミュレーションを終わる)*/ if(num_custs_delayed > num_deleyed_required) sim_run=false; }else{//Limit Time Mode /*Quit the simulation when time to simulation end.(シミュレーションの終了時間になったらシミュレーションを終わる)*/ if(next_event_type==3) sim_run=false; } } /*Invoke the report generator and end the simulation.(レポートを出力してシミュレーションを修了)*/ if(!limit_time_mode) report();//Limit Customer Number Mode fclose(infile); fclose(outfile); return 0; }