//Takes one argument the number of queues to use.
//case 1) 2 queues = ULE
//case 2) #>2 queues = 4BSD
int main(int argc, char *argv[]){
	//gets the start time
	struct timeval startC;
	gettimeofday(&startC, NULL);

	//creates intial PCB array
	procBlock = malloc( sizeof(procInfo));
	//checks for args
	if(argc > 1 && atoi(argv[1]) >1){
		numQueue = atoi(argv[1]);
		queueS = malloc( sizeof(qNode)* numQueue);
		queueE = malloc( sizeof(qNode) * numQueue);
		//runs simulate
		Simulate(NUMROUNDS, TIMESLICE);
	}else{
		printf("Didn't supply the number of queues to create aborting or supplied with only one queue \n");
		exit(1);
	}
	//grabs the ending time
	struct timeval endC;
	gettimeofday(&endC, NULL);

	//data prints
	printf("Time program ran for is %ld ms\n",((endC.tv_sec * 1000 + endC.tv_usec/1000) - (startC.tv_sec * 1000 + startC.tv_usec/1000)));
	int i;
	for(i =0; i < numProc; i++){
		if( procBlock[i]->readyTimes.numProc>0){
			printf("	Process with ID %d was in the ready queue with an average of %f ms, max of %ld ms, and a min of %ld ms\n",
				procBlock[i]->ppid,
				 ((double)(procBlock[i]->readyTimes.avg))/procBlock[i]->readyTimes.numProc,
				  (procBlock[i]->readyTimes.max),
				  (procBlock[i]->readyTimes.min));
			if(procBlock[i] ->ioTimes.numProc > 0){
				printf("		it spent an average of %f ms, max of %ld ms, and min of %ld ms on IO responsiveness\n",
					((double)(procBlock[i]->ioTimes.avg))/procBlock[i]->ioTimes.numProc,
					(procBlock[i]->ioTimes.max),
					(procBlock[i]->ioTimes.min));
			} else {
				printf("		process didn't do any IO waiting\n");
			}
		} else {
			printf("	Process with PID %d was never dispatched\n", procBlock[i]->ppid);
		}
		
	}
	printf("Time program spent on scheduler overheads is %ld ms\n",  ((endC.tv_sec * 1000 + endC.tv_usec/1000) - (startC.tv_sec * 1000 + startC.tv_usec/1000)) -overhead);
	exit(0);
}
    //
    // Image::Notify
    //
    void Image::Notify(U32 crc)
    {
      switch (crc)
      {
        case 0xC3AC47E6: // "Render::PostIFace2"
        {
          F32 curr = Simulate();

          // Calculate screen rectangle
          const ClipRect &rc = cineViewPort;
          ClipRect newRc;

          if (absolute)
          {
            if (absPos.x < 0)
            {
              newRc.p0.x = rc.p1.x - absSize.x + absPos.x;
            }
            else
            {
              newRc.p0.x = rc.p0.x + absPos.x;
            }

            if (absPos.y < 0)
            {
              newRc.p0.y = rc.p1.y - absSize.y + absPos.y;
            }
            else
            {
              newRc.p0.y = rc.p0.y + absPos.y;
            }

            newRc.p1 = newRc.p0 + absSize;
          }
          else
          {
            newRc.p0.x = rc.p0.x + Utils::FtoL(pos.x * F32(rc.Width()));
            newRc.p0.y = rc.p0.y + Utils::FtoL(pos.y * F32(rc.Height()));
            newRc.p1.x = rc.p0.x + Utils::FtoL((pos.x + size.x) * F32(rc.Width()));
            newRc.p1.y = rc.p0.y + Utils::FtoL((pos.y + size.y) * F32(rc.Height()));
          }
          IFace::RenderRectangle(newRc, clr, &texture, curr * IFace::data.alphaScale);

          return;
        }
      }
    }
int main(int argc, char** argv) {
    if(argc ==  3){
        /*Set function pointers to appropriate algorithm */
        if (strcmp(argv[1], "-4bsd") == 0){
            initbsd();
            __ready = &bsd_ready;
            __dispatch = &bsd_dispatch;
            __wait = &bsd_wait;
            __terminate = &bsd_terminate;
            __newprocess = &bsd_newproc;
        } else if(strcmp(argv[1], "-ule") == 0){
            initule();
            __ready = &ule_ready;
            __dispatch = &ule_dispatch;
            __wait = &ule_wait;
            __terminate = &ule_terminate;
            __newprocess = &ule_newproc;                       

        } else{
            usage();
            exit(EXIT_FAILURE);
        }

        timeslice = atoi(argv[2]);

    } else{
        usage();
        exit(EXIT_FAILURE);
    }


    gettimeofday(&time_start, NULL);    

    init_termq();

    printf("Running Simulation with timeslice=%d for %d rounds...\n", timeslice, ROUNDS);

	/* Simulate for 1000 rounds */
	Simulate(ROUNDS, timeslice);

    print_stats(termq);

    return 0;
}
Beispiel #4
0
void Application::Update()
{
    SDL_Event event;
    while (SDL_PollEvent(&event))
    {
        if (event.type == SDL_EventType::SDL_QUIT)
        {
            _running = false;
        }
    }

    _input.Update();

    if (_input.KeyPressed(SDL_SCANCODE_SPACE)) { _updateScene = !_updateScene; }
    if (_input.KeyPressed(SDL_SCANCODE_G)) { _useDeferredShading = !_useDeferredShading; }
    if (_input.KeyPressed(SDL_SCANCODE_T)) { _showTangents = !_showTangents; }
    if (_input.KeyPressed(SDL_SCANCODE_R)) { _renderer.sortEnabled = !_renderer.sortEnabled; }
    if (_input.KeyPressed(SDL_SCANCODE_F))
    {
        //Toggle shadow maps
        for (size_t i = 0; i < _lights.size(); i++)
        {
            if (_lights[i].shadowMap == nullptr) { _lights[i].shadowMap = &_shadowMaps[i]; }
            else { _lights[i].shadowMap = nullptr; }
        }
    }
    if (_input.KeyPressed(SDL_SCANCODE_MINUS)) { _renderer.ignoreCount++; }
    if (_input.KeyPressed(SDL_SCANCODE_EQUALS)) { _renderer.ignoreCount = Math::Max(_renderer.ignoreCount - 1, 0); }
    //std::cout << "Ignoring: " << _renderer.ignoreCount << std::endl;

    Simulate();
    RenderShadowMaps();
    if (_useDeferredShading)
    {
        RenderDeferred();
    }
    else
    {
        RenderForward();
    }

    SDL_GL_SwapWindow(_window);
}
    //
    // Simulation
    //
    void Mesh::Notify(U32 crc)
    {
      switch (crc)
      {
        case 0xEF30A860: // "Render::PostObject"
        {
          Simulate();

          if (root && !done)
          {
            Matrix mat = Vid::CurCamera().WorldMatrix();
            Vector vect;
            mat.Transform( vect, offset);
            mat.posit = vect;
            root->Render( mat);
          }
          return;
        }
      }
    }
    //
    // Simulation
    //
    void Text::Notify(U32 crc)
    {
      switch (crc)
      {
        case 0xC3AC47E6: // "Render::PostIFace2"
        {
          F32 curr = Simulate();

          // Draw the text
          if (text)
          {
            S32 width = font->Width(text, len);
            S32 height = font->Height();
            S32 xpos = Max<S32>(Utils::FtoL(F32(Vid::backBmp.Width() - width) * x), 0);
            S32 ypos = Max<S32>(Utils::FtoL(F32(Vid::backBmp.Height() - height) * y), 0);
            font->Draw(xpos, ypos, text, len, clr, NULL, curr);
          }
          return;
        }
      }
    }
Beispiel #7
0
void World::TickAndRender()
{
	Simulate(_simulateOn);

	// Setup the camera matrix.
	theCamera.Render();

	DrawRenderables();

	// Give the GameManager a chance to draw something.
	if (_gameManager)
		_gameManager->Render();

	//Render debug information
	theSpatialGraph.Render();

	DrawDebugItems();

	//Draw developer console
	_console->Render();
}
Beispiel #8
0
int main(int argc, char *argv[])
{
    ConfigMap cmap;

    if (ParseCmdLine(argc, argv, cmap) != OK)
    {
        exit(0);
    }

    auto queue = makeQueue<Process>();

    uint64_t seconds = Utils::getTimeStamp();
    uint64_t stopTS = Utils::getTimeStamp() + (boost::get<uint64_t>(cmap["sim_time"]) * MILLISECONS_IN_A_SECOND);

    auto t1 = Utils::Time();

    auto algorithm = bindSimulator(getAlgorithmByString(boost::get<std::string>(cmap["algorithm"])));

    auto pg = ProcessGenerator::createGenerator(queue);

    std::this_thread::sleep_for(std::chrono::seconds(1));

    algorithm.Simulate(queue);

    while (seconds <= stopTS)
    {
        seconds = Utils::getTimeStamp();
    }
    
    algorithm.Stop();
    pg->Stop();

    auto t2 = Utils::Time();

    ShowStats(algorithm.getStats(), boost::get<std::string>(cmap["algorithm"]));

    std::cout << "Executing stuff for " << Utils::Diff(t1, t2) / MICROSECONS_IN_A_SECOND << " seconds" << std::endl;

    return 0;
}
Beispiel #9
0
int main(int argc, char *argv[])
{
    int n, G;
    int rank, p;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &p);

    printf("my rank = %d\n", rank);
    printf("Rank = %d: number of processes = %d\n", rank, p);

    if(argc == 3)
    {
        n = argv[1];
        G = argv[2];
    }
    else
        get_input(&n, &G);

    Simulate(n, G, GenerateInitialGoL(n));

    MPI_Finalize();
}
	void iPhysicsWorld::Update(float afTimeStep)
	{
		//Clear all contact points.
		mvContactPoints.clear();

		////////////////////////////////////
		//Update controllers
		tPhysicsControllerListIt CtrlIt = mlstControllers.begin();
		for(; CtrlIt != mlstControllers.end(); ++CtrlIt)
		{
			iPhysicsController *pCtrl = *CtrlIt;

			pCtrl->Update(afTimeStep);
		}


		////////////////////////////////////
		//Update character bodies
		unsigned int lTime = GetApplicationTime();
		tCharacterBodyListIt CharIt = mlstCharBodies.begin();
		for(; CharIt != mlstCharBodies.end(); ++CharIt)
		{
			iCharacterBody *pBody = *CharIt;

			//for(int i=0; i<20; ++i)
			{
				pBody->Update(afTimeStep);//20.0f);
			}
		}
		//LogUpdate(" Updating chars took %d ms\n",mpWorld3D->GetSystem()->GetLowLevel()->GetTime() - lTime);


		////////////////////////////////////
		//Update the rigid bodies before simulation.
		tPhysicsBodyListIt BodyIt = mlstBodies.begin();
		for(; BodyIt != mlstBodies.end(); ++BodyIt)
		{
			iPhysicsBody *pBody = *BodyIt;

			pBody->UpdateBeforeSimulate(afTimeStep);

		}

		////////////////////////////////////
		//Simulate the physics
		lTime = GetApplicationTime();
		Simulate(afTimeStep);
		//LogUpdate(" Updating lowlevel physics took %d ms\n",mpWorld3D->GetSystem()->GetLowLevel()->GetTime() - lTime);

		////////////////////////////////////
		//Update the joints after simulation.
		tPhysicsJointListIt JointIt = mlstJoints.begin();
		for(; JointIt != mlstJoints.end(); )
		{
			iPhysicsJoint *pJoint = *JointIt;

			pJoint->OnPhysicsUpdate();

			if(pJoint->CheckBreakage())
			{
				JointIt = mlstJoints.erase(JointIt);
				hplDelete(pJoint);
			}
			else
			{
				++JointIt;
			}
		}
		////////////////////////////////////
		//Update the rigid bodies after simulation.
		BodyIt = mlstBodies.begin();
		for(; BodyIt != mlstBodies.end(); ++BodyIt)
		{
			iPhysicsBody *pBody = *BodyIt;

			pBody->UpdateAfterSimulate(afTimeStep);
		}
	}
    void RunTest(const std::string& rOutputDirName,
                 const std::string& rModelName,
                 const std::vector<std::string>& rArgs,
                 bool testLookupTables=false,
                 double tableTestV=-1000)
    {
        // Copy CellML file (and .out if present) into output dir
        OutputFileHandler handler(rOutputDirName, true);
        FileFinder cellml_file("heart/test/data/cellml/" + rModelName + ".cellml", RelativeTo::ChasteSourceRoot);
        handler.CopyFileTo(cellml_file);
        FileFinder out_file("heart/test/data/cellml/" + rModelName + ".out", RelativeTo::ChasteSourceRoot);
        if (out_file.Exists())
        {
            handler.CopyFileTo(out_file);
        }

        // Create options file
        std::vector<std::string> args(rArgs);
//        args.push_back("--profile");
        CellMLToSharedLibraryConverter converter(true);
        if (!args.empty())
        {
            converter.CreateOptionsFile(handler, rModelName, args);
        }

        // Do the conversion
        FileFinder copied_file(rOutputDirName + "/" + rModelName + ".cellml", RelativeTo::ChasteTestOutput);
        DynamicCellModelLoaderPtr p_loader = converter.Convert(copied_file);
        // Apply a stimulus of -40 uA/cm^2 - should work for all models
        boost::shared_ptr<AbstractCardiacCellInterface> p_cell(CreateCellWithStandardStimulus(*p_loader, -40.0));

        // Check that the default stimulus units are correct
        if (p_cell->HasCellMLDefaultStimulus())
        {
            // Record the existing stimulus and re-apply it at the end
            boost::shared_ptr<AbstractStimulusFunction> original_stim = p_cell->GetStimulusFunction();

            // Tell the cell to use the default stimulus and retrieve it
            boost::shared_ptr<RegularStimulus> p_reg_stim = p_cell->UseCellMLDefaultStimulus();

            if (rModelName!="aslanidi_model_2009") // Even before recent changes aslanidi model has stimulus of -400 !
            {
                // Stimulus magnitude should be approximately between -5 and -81 uA/cm^2
                TS_ASSERT_LESS_THAN(p_reg_stim->GetMagnitude(),-5);
                TS_ASSERT_LESS_THAN(-81,p_reg_stim->GetMagnitude());
            }

            // Stimulus duration should be approximately between 0.1 and 5 ms.
            TS_ASSERT_LESS_THAN(p_reg_stim->GetDuration(),6.01);
            TS_ASSERT_LESS_THAN(0.1,p_reg_stim->GetDuration());

            // Stimulus period should be approximately between 70 (for bondarenko - seems fast! - would expect 8-10 beats per second for mouse) and 2000ms.
            TS_ASSERT_LESS_THAN(p_reg_stim->GetPeriod(),2000);
            TS_ASSERT_LESS_THAN(70,p_reg_stim->GetPeriod());

            p_cell->SetIntracellularStimulusFunction(original_stim);
        }

        // Check lookup tables exist if they should
        if (testLookupTables && rModelName != "hodgkin_huxley_squid_axon_model_1952_modified")
        {
            double v = p_cell->GetVoltage();
            p_cell->SetVoltage(tableTestV);
            TS_ASSERT_THROWS_CONTAINS(p_cell->GetIIonic(), "outside lookup table range");
            p_cell->SetVoltage(v);
        }
        Simulate(rOutputDirName, rModelName, p_cell);
    }
int main (int argc, char*argv[])
{
   char *MCctlf=NULL, outf[512]="evolver.out", treefile[512]="mcmc.txt", mastertreefile[512]="\0";
   int i, option=-1, ntree=1,rooted, BD=0, gotoption=0, pick1tree=-1;
   double bfactor=1, birth=-1,death=-1,sample=-1,mut=-1, *space;
   FILE *fout=gfopen(outf,"w");

   printf("EVOLVER in %s\n", pamlVerStr);
   com.alpha=0; com.cleandata=1; com.model=0; com.NSsites=0;

   if(argc>1) {
      gotoption=1;   sscanf(argv[1], "%d", &option);
   }
   if(argc==1)
      printf("Results for options 1-4 & 8 go into %s\n",outf);
   else if(option!=5 && option!=6 && option!=7 && option!=9) {
      puts("Usage: \n\tevolver \n\tevolver option# MyDataFile"); exit(-1); 
   }
   if(option>=4 && option<=6)
      MCctlf = argv[2];
   else if(option==9) {
      strcpy(treefile, argv[2]);
      if(argc>3) strcpy(mastertreefile, argv[3]);
      if(argc>4) sscanf(argv[4], "%d", &pick1tree);
   }

#if defined (CodonNSbranches)
   option=6;  com.model=1; 
   MCctlf = (argc==3 ? argv[2] : "MCcodonNSbranches.dat");
   gotoption = 1;
#elif defined (CodonNSsites)
   option=6;  com.NSsites=3; 
   MCctlf = (argc==3 ? argv[2] : "MCcodonNSsites.dat");
   gotoption = 1;
#elif defined (CodonNSbranchsites)
   option=6;  com.model=1; com.NSsites=3; 
   MCctlf = (argc==3 ? argv[2] : "MCcodonNSbranchsites.dat");
   gotoption = 1;
#endif

   if(!gotoption) {
      for(; ;) {
         fflush(fout);
         printf("\n\t(1) Get random UNROOTED trees?\n"); 
         printf("\t(2) Get random ROOTED trees?\n"); 
         printf("\t(3) List all UNROOTED trees?\n");
         printf("\t(4) List all ROOTED trees?\n");
         printf("\t(5) Simulate nucleotide data sets (use %s)?\n",MCctlf0[0]);
         printf("\t(6) Simulate codon data sets      (use %s)?\n",MCctlf0[1]);
         printf("\t(7) Simulate amino acid data sets (use %s)?\n",MCctlf0[2]);
         printf("\t(8) Calculate identical bi-partitions between trees?\n");
         printf("\t(9) Calculate clade support values (evolver 9 treefile mastertreefile <pick1tree>)?\n");
         printf("\t(11) Label clades?\n");
         printf("\t(0) Quit?\n");

         option = 9;
         scanf("%d", &option);

         if(option==0) exit(0);
         if(option>=5 && option<=7) break;
         if(option<5)  { 
            printf ("No. of species: ");
            scanf ("%d", &com.ns);
         }
         if(com.ns>NS) error2 ("Too many species.  Raise NS.");
         if((space=(double*)malloc(10000*sizeof(double)))==NULL) error2("oom");
         rooted = !(option%2);
         if(option<3) {
            printf("\nnumber of trees & random number seed? ");
            scanf("%d%d", &ntree, &i);
            SetSeed(i, 1);
            printf ("Want branch lengths from the birth-death process (0/1)? ");
            scanf ("%d", &BD);
         }
         if(option<=4) {
            if(com.ns<3) error2("no need to do this?");
            i = (com.ns*2-1)*sizeof(struct TREEN);
            if((nodes=(struct TREEN*)malloc(i)) == NULL) 
               error2("oom");
         }
         switch (option) {
         case(1):   /* random UNROOTED trees */
         case(2):   /* random ROOTED trees */
            /* default names */
            if(com.ns<=52)
               for(i=0; i<com.ns; i++)  sprintf(com.spname[i], "%c", (i<26 ? 'A'+i : 'a'+i-26));
            else
               for(i=0; i<com.ns; i++)  sprintf(com.spname[i], "S%d", i+1);

            if(BD) {
               printf ("\nbirth rate, death rate, sampling fraction, and ");
               printf ("mutation rate (tree height)?\n");
               scanf ("%lf%lf%lf%lf", &birth, &death, &sample, &mut);
            }
            for(i=0;i<ntree;i++) {
               RandomLHistory (rooted, space);
               if(BD)
                  BranchLengthBD (1, birth, death, sample, mut);
               if(com.ns<20&&ntree<10) { OutTreeN(F0, 0, BD); puts("\n"); }
               OutTreeN(fout, 1, BD);  FPN(fout);
            }
            /*
            for (i=0; i<com.ns-2-!rooted; i++)
               Ib[i] = (int)((3.+i)*rndu());
            MakeTreeIb (com.ns, Ib, rooted);
            */
            break;
         case(3):
         case(4): 
            ListTrees(fout, com.ns, rooted);
            break;
         case(8):  TreeDistances(fout);  break;
         case(9):  
            printf("tree file names? ");
            scanf("%s%s", treefile, mastertreefile);
            break;
         case(10): between_f_and_x();    break;
         case(11): LabelClades(fout);    break;
         default:  exit(0);
         }
      }
   }

   if(option>=5 && option<=7) {
      com.seqtype = option-5;  /* 0, 1, 2 for bases, codons, & amino acids */
      Simulate(MCctlf ? MCctlf : MCctlf0[option-5]);
   }
   else if(option==9) {
      CladeSupport(fout, treefile, mastertreefile, pick1tree);
      /* CladeMrBayesProbabilities("/papers/BPPJC3sB/Karol.trees"); */
   }
   return(0);
}
Beispiel #13
0
static void simLoop (int pause)
{

	Simulate(pause);
}
Beispiel #14
0
void World::Tick()
{
	Simulate(_simulateOn);
}
Beispiel #15
0
bool ESoundSource::Load(IReader& F)
{
	u32 version 	= 0;

    if(F.r_chunk(SOUND_CHUNK_VERSION,&version)){
        if(version!=SOUND_SOURCE_VERSION){
            ELog.Msg( mtError, "ESoundSource: Unsupported version.");
            return false;
        }
    }else return false;

	inherited::Load			(F);

    R_ASSERT(F.find_chunk(SOUND_CHUNK_TYPE));
	m_Type					= ESoundType(F.r_u32());

    R_ASSERT(F.find_chunk(SOUND_CHUNK_SOURCE_NAME));
    F.r_stringZ		(m_WAVName);

    
    if (F.find_chunk(SOUND_CHUNK_SOURCE_PARAMS3)){
       	m_Params.base_volume	= 1.f;
    	F.r_fvector3			(m_Params.position);
       	m_Params.volume			= F.r_float();
        m_Params.freq			= F.r_float();
        m_Params.min_distance	= F.r_float();
        m_Params.max_distance	= F.r_float();
        m_Params.max_ai_distance= F.r_float();
    }else if (F.find_chunk(SOUND_CHUNK_SOURCE_PARAMS2)){
       	m_Params.base_volume	= 1.f;
    	F.r_fvector3			(m_Params.position);
       	m_Params.volume			= F.r_float();
        m_Params.freq			= F.r_float();
        m_Params.min_distance	= F.r_float();
        m_Params.max_distance	= F.r_float();
        m_Params.max_ai_distance= F.r_float();
    }else{
    	if (!F.find_chunk(SOUND_CHUNK_SOURCE_PARAMS)){
            ELog.DlgMsg( mtError, "ESoundSource: Can't load Sound Source '%s'. Unsupported version.",*m_WAVName);
            return false;
        }
       	m_Params.base_volume	= 1.f;
    	F.r_fvector3			(m_Params.position);
       	m_Params.volume			= F.r_float();
        m_Params.freq			= F.r_float();
        m_Params.min_distance	= F.r_float();
        m_Params.max_distance	= F.r_float();
        m_Params.max_ai_distance= m_Params.max_distance;
    }

    if(F.find_chunk(SOUND_CHUNK_SOURCE_FLAGS))
		F.r			(&m_Flags,sizeof(m_Flags));
    

    if(F.find_chunk(SOUND_CHUNK_GAME_PARAMS)){
	    F.r_fvector2			(m_RandomPause);
    	F.r_fvector2			(m_ActiveTime);
	    F.r_fvector2			(m_PlayTime);
	}
    
    ResetSource		();

    switch (m_Type){
    case stStaticSource: 
    	if (m_Flags.is(flPlaying)) 		Play(); 
    	if (m_Flags.is(flSimulating)) 	Simulate(); 
    break;
    default: THROW;
    }
    return true;
}
Beispiel #16
0
int main(int argc,char *argv[])
{
	int rank, p, N, G,X;

    struct timeval t1, t2, t3, t4;

    // Change this "N" from 2 up to 16

    N = 16;

    p = 2;

    G = atoi(argv[1]);

//    X = 3;

    X = 1;

    MPI_Init(&argc, &argv);

    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    MPI_Comm_size(MPI_COMM_WORLD, &p);



    //Timing for total runtime

    struct timeval totalRuntimeStart, totalRuntimeEnd;

    int totalRuntime;



    // Timing for average time per generation(excluding display)

    struct timeval avgPerGenerationStart, avgPerGenerationEnd;

    int averageTimePerGeneration;

    int tempTime=0;


    // Average time per the display function

    struct timeval displayRuntimeStart, displayRuntimeEnd;

    int averageDisplayTimePerGeneration;

    int displayTempTime;

    int displayMethodCounter = 0;





    // Time for different communication steps.

    struct timeval mpiCallRuntimeStart, mpiCallRuntimeEnd;





    int MAX_SIZE = 30;

    int MAX_TRIAL = 100;

    int userInput;


    int randomseed[p];

    srand(time(NULL));

    gettimeofday(&totalRuntimeStart, NULL);
	int i;
    if(rank == 0)
    {
    	for (i = 0; i < p; i++)
    	            randomseed[i] = rand();
    }
    int received_random;
    int scatterTime;
    gettimeofday(&t3, NULL);
    MPI_Scatter(randomseed, 1, MPI_INT, &received_random, 1,MPI_INT,0, MPI_COMM_WORLD);
    gettimeofday(&t4, NULL);
   
    scatterTime =  (t4.tv_sec-t3.tv_sec)*1000 + (t4.tv_usec-t3.tv_usec)/1000; 
    //printf("%d\t%d", rank, scatterTime);


    int start_index, end_index;

	start_index = rank * (N / p);

	end_index = (rank + 1) * (N / p) - 1;

	int cols_size = (end_index - start_index) +1;

	int effective_cols_size = cols_size + 2;

	int matrix[N][effective_cols_size];


    struct timeval barrier1s,barrier1e;
    int tBarrier = 0;
    int tBarrierAvg = 0;
     //initialize matrix part

    int currentGatherTime = 0;

     GenerateInitialGoL(rank, p, start_index, N, effective_cols_size,matrix,received_random);
     for(i=0;i<G;i++)

            {
             	gettimeofday(&avgPerGenerationStart, NULL);

                gettimeofday(&barrier1s, NULL);
                MPI_Barrier(MPI_COMM_WORLD);
                gettimeofday(&barrier1e, NULL);
                tBarrier += (barrier1e.tv_sec-barrier1s.tv_sec)*1000 + (barrier1e.tv_usec-barrier1s.tv_usec)/1000;
                Simulate(i,rank,N,effective_cols_size,matrix,p);

                if(i%X==0)

                {
                    gettimeofday(&displayRuntimeStart, NULL);

                    currentGatherTime += DisplayGoL(N, effective_cols_size, matrix,rank);

                    gettimeofday(&displayRuntimeEnd, NULL);

                    displayTempTime += ((displayRuntimeEnd.tv_sec-displayRuntimeStart.tv_sec)*1000 + ((displayRuntimeEnd.tv_usec - displayRuntimeStart.tv_usec)/1000));

                    displayMethodCounter++;
                }

                gettimeofday(&avgPerGenerationEnd, NULL);

                //printf("START: %d\n ", avgPerGenerationStart.tv_sec);
                //printf("END: %d\n ", avgPerGenerationEnd.tv_sec);
                tempTime+= ((avgPerGenerationEnd.tv_sec-avgPerGenerationStart.tv_sec)*1000 + ((avgPerGenerationEnd.tv_usec - avgPerGenerationStart.tv_usec)/1000));





            }

                tBarrierAvg = tBarrier / G; 
                averageTimePerGeneration = tempTime/G;

            // Average the number of times the display method was called.

            averageDisplayTimePerGeneration = displayTempTime / displayMethodCounter;
            currentGatherTime = currentGatherTime / displayMethodCounter;




            // Get the total runtime

            gettimeofday(&totalRuntimeEnd, NULL);

            totalRuntime = (totalRuntimeEnd.tv_sec - totalRuntimeStart.tv_sec)*1000 + (totalRuntimeEnd.tv_usec - totalRuntimeStart.tv_usec)/1000;

    //printf("%d\t%d\n",rank, totalRuntime);
    //printf("%d\t%d\n",rank, tBarrierAvg);
    //printf("RANK: %d     AVERAGE RUNTIME PER GENERATION: %d\n", rank, averageTimePerGeneration);

   // printf("RANK: %d     AVERAGE TIME PER DISPLAY METHOD: %d\n\n\n", rank, averageDisplayTimePerGeneration);
    printf("%d\t%d\n", rank, currentGatherTime);


    MPI_Finalize();

    //This will output the array.



}
Beispiel #17
0
void CGameServer::Think(double flHostTime)
{
	TPROF("CGameServer::Think");

	m_iFrame++;
	m_flFrameTime = flHostTime - m_flHostTime;

	m_flFrameTime *= m_flTimeScale;

	// If the framerate drops, don't let too much happen without the player seeing
	if (GameNetwork()->IsConnected())
	{
		// But not as much in multiplayer games where we need to keep the game time synchronized
		if (m_flFrameTime > 1.0f)
			m_flFrameTime = 1.0f;
	}
	else
	{
		if (m_flFrameTime > 0.15f)
			m_flFrameTime = 0.15f;
	}

	m_flGameTime += m_flFrameTime;

	m_flHostTime = flHostTime;

	if (GameNetwork()->IsConnected() && GameNetwork()->IsHost() && m_flHostTime > m_flNextClientInfoUpdate)
	{
		m_flNextClientInfoUpdate = m_flHostTime + 5.0f;

		size_t iClientsConnected = GameNetwork()->GetClientsConnected();
		for (size_t i = 0; i < iClientsConnected; i++)
		{
			size_t iClient = GameNetwork()->GetClientConnectionId(i);
			if (iClient == ~0)
				continue;

			GameNetwork()->CallFunction(iClient, "ClientInfo", iClient, GetGameTime());
		}
	}

	// Erase anything deleted last frame.
	for (size_t i = 0; i < m_ahDeletedEntities.size(); i++)
		delete m_ahDeletedEntities[i];

	m_ahDeletedEntities.clear();

	if (CWorkbench::IsActive())
		Workbench()->Think();

	CNetwork::Think();

	size_t iMaxEntities = GameServer()->GetMaxEntities();
	for (size_t i = 0; i < iMaxEntities; i++)
	{
		CBaseEntity* pEntity = CBaseEntity::GetEntity(i);
		if (!pEntity)
			continue;

		pEntity->Think();

		if (m_bHalting)
			break;
	}

	Simulate();

	Think();

	if (GameNetwork()->IsHost())
		CGameServerNetwork::UpdateNetworkVariables(NETWORK_TOCLIENTS);

	if (GameNetwork()->IsHost())
	{
		for (size_t i = 0; i < iMaxEntities; i++)
		{
			CBaseEntity* pEntity = CBaseEntity::GetEntity(i);
			if (!pEntity)
				continue;

			if (!pEntity->HasIssuedClientSpawn())
				pEntity->IssueClientSpawn();

			if (m_bHalting)
				break;
		}
	}

	CParticleSystemLibrary::Simulate();

	TPortal_Think();
}
void NBodySimulator::Simulate(BodyList &bodies, const double time_simulated)
{
  Simulate(bodies, time_simulated, nullptr);
}