コード例 #1
0
ファイル: regulator.cpp プロジェクト: KamiNeko/gaggia-pi
void Regulator::_worker() {
    // Start time and next time step
    double start = getClock();
    double next  = start;
            
    while ( _run ) {
        // get elapsed time since start
        //double elapsed = getClock() - start;

        // take temperature measurement
        double latestTemp = 0.0;
    
        if ( !_temperature->getDegrees( latestTemp ) ) {
            latestTemp = 0.0;
        }

        // boiler drive (duty cycle)
        double drive = 0.0;

        // if the temperature is near zero, we assume there's an error
        // reading the sensor and drive (duty cycle) will be zero
        if ( _power && latestTemp > 0.5 ) {
            // lock shared data before use
            std::lock_guard<std::mutex> lock( *_mutex );

            // calculate next time step
            next += _timeStep;

            // calculate PID update
            drive = _update( _targetTemperature - latestTemp, latestTemp, _iGain, _pGain, _dGain );
        }

        // clamp the output power to sensible range
        if ( drive > 1.0 ) {
            drive = 1.0;
        } 
        else if ( drive < 0.0 ) {
            drive = 0.0;
        }    

        // Set the boiler power (uses pulse width modulation)
        _boiler->setPower( drive );

        // Store the latest temperature reading
        {
            std::lock_guard<std::mutex> lock( *_mutex );
            _latestTemp  = latestTemp;
            _latestPower = drive;
        }

        // sleep for the remainder of the time step
        double remain = next - getClock();
        if ( remain > 0.0 ) {      
            delayms( static_cast<int>(1.0E3 * remain) );
        }
    };

    // Ensure the boiler is turned off before exit
    _boiler->setPower( 0.0 );
}
void atende(int i, Fila *f, Fila *fo){
	Carro* c = NULL;
	std::cout << "inicializando bomba de combustivel " << i << "." << std::endl;

	while (getClock() < 15){   //atende enquanto Clock < 15 segundos
       
		if (f->isEmpty() == false){		//se fila nao vazia atende...			
			mu.lock();
			  c= f->getFirst();			//pega primeiro da fila
			mu.unlock();
			if (c != NULL){				//se conseguiu pegar alguem da fila
				std::cout << " bomba " << i << " atendendo " << c->getPlaca() << " em " << getClock() << std::endl;
				std::this_thread::sleep_for(std::chrono::seconds(2));  //aqui, por exemplo, o valor 2 poderia ser substituido por normal(5,2) =>EXEMPLO!
				std::cout << " bomba " << i << " liberando " << c->getPlaca() << " em " << getClock() << std::endl;

				//sorteia se carro vai para troca de oleo ou nao
				//chance de ir para troca de oleo é de 30% neste exemplo...
				//se nao for para troca de oleo carro é destruido...
				//Obs.: substituir uso do rand() pelo random LCG thread safe 
				if ((rand()%100) < 30) fo->insert(c);
				else delete c;
				c = NULL;
			}
		}         
		
	}
	std::cout << "encerrando processo bomba... " << i << std::endl;
}
コード例 #3
0
ファイル: SevenSeg.c プロジェクト: jwchong93/RTOS-practise
void sevenSegmentSM(SevenSegmentData *data) {
  switch(data->state) {
    case _7SEG_INIT:
      init7SegmentHardware();
      data->count = 0;
      data->currentClock = getClock();
      write7Segment(data->count);
      data->state = _7SEG_WAITING;
      break;

    case _7SEG_WAITING:
      if(getClock() - data->currentClock >= MSEC_150) {
        data->count++;
        if(data->count >= 15)
          data->count = 0;
        write7Segment(data->count);
        data->currentClock = getClock();
      }
      data->state = _7SEG_WAITING;
      break;

    default:
      data->state = _7SEG_INIT;
      break;
  }
}
コード例 #4
0
ファイル: timer.cpp プロジェクト: blaztinn/piglit
///////////////////////////////////////////////////////////////////////////////
// waitForTick:  wait for beginning of next system clock tick; return the time.
///////////////////////////////////////////////////////////////////////////////
double
Timer::waitForTick() {
	double start;
	double current;

	start = getClock();

	// Wait for next tick:
	while ((current = getClock()) == start)
		;

	// Start timing:
	return current;
} // Timer::waitForTick
コード例 #5
0
/*
 *Creating Game Clock linked list
 */
GameClock createClock()	{
    GameClock clock = (GameClock) malloc(sizeof(*clock));
    clock->first = NULL;
    clock->last = NULL;
    getClock(clock);
    return clock;
}
コード例 #6
0
ファイル: PeriodicEngines.hpp プロジェクト: DEMANY/trunk
		virtual bool isActivated(){
			const Real& virtNow=scene->time;
			Real realNow=getClock();
			const long& iterNow=scene->iter;
			
			if((firstIterRun > 0) && (nDone==0)) {
				if((firstIterRun > 0) && (firstIterRun == iterNow)) {
					realLast=realNow; virtLast=virtNow; iterLast=iterNow; nDone++;
					return true;
				}
				return false;
			}
			
			if (iterNow<iterLast) nDone=0;//handle O.resetTime(), all counters will be initialized again
			if((nDo<0 || nDone<nDo) &&
				((virtPeriod>0 && virtNow-virtLast>=virtPeriod) ||
				 (realPeriod>0 && realNow-realLast>=realPeriod) ||
				 (iterPeriod>0 && iterNow-iterLast>=iterPeriod))){
				realLast=realNow; virtLast=virtNow; iterLast=iterNow; nDone++;
				return true;
			}
			
			if(nDone==0){
				realLast=realNow; virtLast=virtNow; iterLast=iterNow; nDone++;
				if(initRun) return true;
				return false;
			}
			return false;
		}
コード例 #7
0
ファイル: main.c プロジェクト: parkerpatriot/space-invaders
// This is invoked in response to a timer interrupt.
// It does 2 things: 1) debounce switches, and 2) advances the time.
void timer_interrupt_handler() {
	uint32_t seconds = 0;
	uint32_t minutes = 0;
	uint32_t hours = 0;

	if (++counter == ONE_SECOND && !in_auto_increment_mode()){
		// clear the counter, it's been a second
		counter = 0;

		// increment the clock
		incrementClock();
	} else if (++refresh_counter == FAST_COUNT_MAX) {
		// clear the counter, it's time to refresh
		refresh_counter = 0;

		// grab the clock values so we can print them out
		getClock(&seconds, &minutes, &hours);

		// make sure to backspace so clock changes in place
		xil_printf("\b\b\b\b\b\b\b\b%02d:%02d:%02d", hours, minutes, seconds);
	}

	// let the bouncer know an interrupt occurred so it can debounce the button
	if (bouncing) tick_bouncer();

}
コード例 #8
0
void display_layout2_print_datetime(Ucglib_ILI9341_18x240x320_HWSPI ucg) {
 if (getClock()){
  SERIAL_OUT.println("Refresh Clock "); 
  ucg.setFontMode(UCG_FONT_MODE_SOLID);
  ucg.setFont(FONT_SMALL);
  ucg.setFontPosTop();
  //NTP
  String dateAndTime = "";
  if (now() != prev2Display) { //update the display only if time has changed
    prev2Display = now();
    //NTP
    ////////////////////////////////////////////////////////////////////////////
    String Time = "";
    String Date = "";
    Time = digitalClockDisplay_simple();
    Date = digitalDataDisplay();
    //ucg.setFont(ucg_font_inr19_mf);
    ucg.setFont(ucg_font_helvB14_hf);
    ucg.setColor(0, 255, 255, 255);       // Bianco
    ucg.setPrintPos(160, 4);
    ucg.print(Date);
    //ucg.setFont(ucg_font_inb21_mr);
    ucg.setFont(ucg_font_helvB18_hf);
    ucg.setPrintPos(260, 4);
    ucg.print(Time);
    SERIAL_OUT.print("New Clock: "); SERIAL_OUT.println(Time);
  }
 }
}
コード例 #9
0
ファイル: XGameMap.cpp プロジェクト: albertclass/XStudio
	xgc_void XGameMap::CreateClock( xgc_lpcstr lpName, xgc_lpcstr lpStart, xgc_lpcstr lpParam, xgc_lpcstr lpDuration )
	{
		auto it = mMapClock.find( lpName );
		if( it != mMapClock.end() )
		{
			USR_WRN( "场景[%s]创建定时器[%s]时发现定时器已存在。", getString( XGameMap::MapIndex ), lpName );
			return;
		}

		datetime dt_start, dt_close;
		datetime now = datetime::now();

		if( strncasecmp( "relative", lpStart, 8 ) == 0 )
		{
			dt_start = datetime::relative_time( timespan::convert( lpStart + 8 ) );
		}
		else
		{
			dt_start = datetime::convert( lpStart );
		}

		timespan ts_duration = lpDuration ? timespan::convert( lpDuration ) : timespan( 0 );

		xgc_char szDateTime[64] = { 0 };
		DBG_TIP( "场景%s创建定时器%s 触发时间为%s", getString( XGameMap::MapName ), lpName, dt_start.to_string( szDateTime, sizeof( szDateTime ) ) );

		auto evt = MakeEvent< XGameMapEvent >( evt_map_clock );
		evt->alias = it->first.c_str();

		mMapClock[lpName] = getClock().insert(
			std::bind( (XEventBind3)&XObject::EmmitEvent, this, &evt->cast, DeleteEvent< XGameMapEvent > ),
			dt_start, ts_duration, lpParam );
	}
コード例 #10
0
ファイル: SchedulerTimer.C プロジェクト: BillTheBest/k42
SysTime
SchedulerTimer::SysTimeNowInternal()
{
    SysTime retvalue;
    retvalue = usermodeClock ?
	getClock() : _TIMER_REQUEST(0, TimerEvent::queryNow);
    return (retvalue);
}
コード例 #11
0
ファイル: wizSystem.c プロジェクト: sobhamo/hello-world
int _gettimeofday(struct timeval *tv,struct timezone *tzvp)
{
	tv->tv_sec = time_dat;
	tv->tv_usec = time_dat+getClock()%1000;
	tzvp->tz_dsttime = 540;
	tzvp->tz_dsttime = DST_NONE;
	return 0;
}
コード例 #12
0
ファイル: clock.c プロジェクト: alexcb/Chuckdaw
void addClock(long long value)
{
	if( !stubClock ) {
		stubClockTime = getClock();
		stubClock = true;
	}
	stubClockTime += value;
}
コード例 #13
0
/*
 * startClock()
 *
 * Start the profiling clock.
 */
void startClock(void)
{
#ifdef _WIN32
  start = getClock();
#else
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
#endif
}
コード例 #14
0
ファイル: timer.cpp プロジェクト: blaztinn/piglit
///////////////////////////////////////////////////////////////////////////////
// chooseRunTime:  Select an appropriate runtime for benchmarks.
//	By running for at least 10000 ticks, and attempting to keep timing
//	accurate to one tick, we hope to make our results repeatable.
//	(ignoring all the other stuff that might be going on in	the system,
//	of course).  Long runs reduce the effect of measurement error, but
//	short runs reduce the chance that some other process on the system
//	will steal time.
///////////////////////////////////////////////////////////////////////////////
double
Timer::chooseRunTime() {
	double start = getClock();
	double finish;

	// Wait for next tick:
	while ((finish = getClock()) == start)
		;
	
	// Run for 10000 ticks, clamped to [0.1 sec, 5.0 sec]:
	double runTime = 10000.0 * (finish - start);
	if (runTime < 0.1)
		runTime = 0.1;
	else if (runTime > 5.0)
		runTime = 5.0;

	return runTime;
} // Timer::chooseRunTime
コード例 #15
0
ファイル: fb.cpp プロジェクト: ascendancy721/gnash
bool
FBGui::run()
{
//  GNASH_REPORT_FUNCTION;

#ifdef USE_TSLIB
    int ts_loop_count = 0;
#endif

    VirtualClock& timer = getClock();
    int delay = 0;
    
    // let the GUI recompute the x/y scale factors to best fit the whole screen
    resize_view(_validbounds.width(), _validbounds.height());

    float fps = getFPS();
    
    // FIXME: this value is arbitrary, and will make any movie with
    // less than 12 frames eat up more of the cpu. It should probably
    // be a much lower value, like 2.
    if (fps > 12) {
        delay = static_cast<int>(100000/fps);
    } else {
        // 10ms per heart beat
        delay = 10000;
    }
    // log_debug(_("Movie Frame Rate is %d, adjusting delay to %dms"), fps,
    //           _interval * delay);
    
    // This loops endlessly at the frame rate
    while (!terminate_request) {  
        // wait the "heartbeat" inteval. _interval is in milliseconds,
        // but gnashSleep() wants nanoseconds, so adjust by 1000.
        gnashSleep(_interval * 1000);
        // TODO: Do we need to check the real time slept or is it OK when we woke
        // up early because of some Linux signal sent to our process (and thus
        // "advance" faster than the "heartbeat" interval)? - Udo

#ifdef USE_TSLIB
        ts_loop_count++; //increase loopcount
#endif
        
        // check input devices
        checkForData();

        // advance movie  
        Gui::advance_movie(this);

        // check if we've reached a timeout
        if (_timeout && timer.elapsed() >= _timeout ) {
            break;
        }
    }

    return true;
}
コード例 #16
0
ファイル: stats.cpp プロジェクト: jordond/pokerhands
void Stats::printFooter() {
    std::cout << "-----------------------------------------------------" << std::endl;
    std::cout << std::setprecision(3) << std::fixed;
    std::cout << "Hands Generated:\t" << hands_ << std::endl;
    std::cout << "Decks Drawn:\t\t" << hands_ / 10.0 << std::endl;
    std::cout << "Elapsed Time:\t\t" << getClock() << "s" << std::endl;
    if (version_ == "PARALLEL")
        std::cout << "Number of Processes:\t\t" << std::endl;
    std::cout << "-----------------------------------------------------" << std::endl;
}
コード例 #17
0
/*
 * stopClock()
 *
 * Stop the profiling clock.
 */
void stopClock(int which)
{
#ifdef _WIN32
  profile_counter[which] += getClock() - start;
#else
  struct timespec end;
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end);
  profile_counter[which] += end.tv_nsec - start.tv_nsec;
#endif
}
コード例 #18
0
void
ApplicationImpl::checkDB()
{
    getClock().getIOService().post(
        [this]
        {
            checkDBAgainstBuckets(this->getMetrics(), this->getBucketManager(),
                                  this->getDatabase(),
                                  this->getBucketManager().getBucketList());
        });
}
コード例 #19
0
ファイル: dump.cpp プロジェクト: sunarto/gnash
void
DumpGui::writeFrame()
{
    if (! _fileStream.is_open() ) return;

    _fileStream.write(reinterpret_cast<char*>(_offscreenbuf.get()),
            _offscreenbuf_size);

    _lastVideoFrameDump = getClock().elapsed();
    ++_framecount;
}
コード例 #20
0
ClockNode findClock(clockType cType)	{
    GameClock gClock = getClock(NULL);
    ClockNode currNode;
    currNode = gClock->first;
    while(currNode != NULL)	{
        if (currNode->type == cType)	{
            return currNode;
        }
        currNode = currNode->next;
    }
    return 0;
}
コード例 #21
0
/*
 * Add Clock Node
 */
void addClock(clockType type)	{
	
	GameClock clock = getClock(NULL);	
	if(checkUniqueClockType(type))	{
		if(clock->first == NULL)	{
			clock->first = clock->last = createClockNode(type);
		} else {
			clock->last->next = createClockNode(type);
			clock->last = clock->last->next;
		}
	}
}
コード例 #22
0
void freeClocks()	{
    GameClock gClock = getClock(NULL);
    ClockNode currNode = gClock->first;
    ClockNode temp;
    while(currNode != NULL)	{
        temp = currNode->next;
        free(currNode);
        currNode = temp;
    }

    free(gClock);
}
void trocaOleo(Fila *fo){
	Carro* c = NULL;
	std::cout << "inicializando troca de oleo." << std::endl;

	while (getClock() < 25){   //atende enquanto Clock < 25 segundos

		if (fo->isEmpty() == false){		//se fila da troca de oleo nao vazia atende...			
			mu.lock();
			c = fo->getFirst();				//pega primeiro da fila
			mu.unlock();
			if (c != NULL){					//se conseguiu pegar alguem da fila
				std::cout << " trocando oleo de " << c->getPlaca() << " em " << getClock() << std::endl;
				std::this_thread::sleep_for(std::chrono::seconds(5));  //aqui, por exemplo, o valor 5 poderia ser substituido por normal(7,1) =>EXEMPLO!
				std::cout << " terminou troca de " << c->getPlaca() << " em " << getClock() << std::endl;
				delete c;
				c = NULL;
			}
		}

	}
	std::cout << "encerrando processo troca de oleo... " << std::endl;
}
コード例 #24
0
int checkUniqueClockType(clockType type)	{

    GameClock clock = getClock(NULL);
    ClockNode currNode;
    currNode = clock->first;
    while(currNode!= NULL)	{
        if (currNode->type == type)	{
            return 0;
        }
        currNode = currNode->next;
    }

    return 1;

}
コード例 #25
0
ファイル: logger.c プロジェクト: alexcb/Chuckdaw
//void node_debug(struct NodeState *nodeState, char *fmt, ...)
void node_debug(struct NodeState *nodeState, ...)
{
	va_list arg;

	char s[BUFSIZE];

	va_start(arg, nodeState);
	char *fmt = va_arg(arg, char*);
	vsnprintf(s, BUFSIZE, fmt, arg);
	va_end(arg);

	uuid_to_string(nodeID, nodeState->self->ID)

	printf("%lld %s: %s\n", getClock(), nodeID, s);
}
コード例 #26
0
/*
 * Add Clock Node
 */
int addClock(clockType type)	{
    GameClock clock = getClock(NULL);
    if(checkUniqueClockType(type))	{
        if(clock->first == NULL)	{
            clock->first = clock->last = createClockNode(type);
        } else {
            clock->last->next = createClockNode(type);
            clock->last = clock->last->next;
        }
    } else {
        fprintf(stderr,"Attempt to add non unique clock\n");
        return 0;
    }
    return 1;
}
コード例 #27
0
ファイル: plan_stage.cpp プロジェクト: ShaneHarvey/mongo
PlanStage::StageState PlanStage::work(WorkingSetID* out) {
    invariant(_opCtx);
    ScopedTimer timer(getClock(), &_commonStats.executionTimeMillis);
    ++_commonStats.works;

    StageState workResult = doWork(out);

    if (StageState::ADVANCED == workResult) {
        ++_commonStats.advanced;
    } else if (StageState::NEED_TIME == workResult) {
        ++_commonStats.needTime;
    } else if (StageState::NEED_YIELD == workResult) {
        ++_commonStats.needYield;
    }

    return workResult;
}
コード例 #28
0
ファイル: timer.cpp プロジェクト: blaztinn/piglit
///////////////////////////////////////////////////////////////////////////////
// calibrate:  Determine overhead of measurement, initialization routine,
//	and finalization routine
///////////////////////////////////////////////////////////////////////////////
void
Timer::calibrate() {
	double runTime = chooseRunTime();

	preop();

	long reps = 0;
	double current;
	double start = waitForTick();
	do {
		postop();
		++reps;
	} while ((current = getClock()) < start + runTime);

	overhead   = (current - start) / (double) reps;
	calibrated = true;
} // Timer::calibrate
int _tmain(int argc, _TCHAR* argv[])
{
	//captura o tempo inicial da simulação
	tempoInicial = std::chrono::system_clock::now();

	//cria e inicializa contador que sera usado para identificar as placas dos carros
	cntr = 0;

	//cria filas de carros
	Fila f;			//fila de carros a espera de atendimento nas bombas
	Fila fOleo;		//fila de carros na troca de oleo
	
	//cria 3 geradores (de carros)
	std::thread t1(gerador, 1, 2, &f);  //gerador 1, cria carros de 2 em 2 segundos
	std::thread t2(gerador, 2, 5, &f);	//gerador 2, cria carros de 5 em 5 segundos
	std::thread t3(gerador, 3, 7, &f);	//gerador 3, cria carros de 7 em 7 segundos

	//cria 2 bombas para atendimento
	//neste exemplo, as duas bombas "consomem" carros a partir da mesma fila
	//elas tem todas o mesmo tempo de atendimento; isto pode ser alterado no prototipo...
	//as bombas recebem referencias para as duas filas (a de atendimento e a fila oleo)
	//porque elas removem da fila de atendimento e inserem (possivelmente) na fila oleo...
	std::thread t4(atende, 1, &f, &fOleo);	//bomba 1
	std::thread t5(atende, 2, &f, &fOleo);  //bomba 2

	//cria estação de troca de oleo
	//30% dos carros que saem do atendimento vao para troca de oleo
	//os demais sao destruidos logo apos o atendimento
	std::thread t6(trocaOleo, &fOleo);  //troca de oleo

	t1.join();
	t2.join();
	t3.join();
	t4.join();
	t5.join();
	t6.join();

	std::cout << "encerrando... " << getClock() << std::endl;

	cin.get();

	return 0;
}
void gerador(int i, int tempo,  Fila *f){

	int placa;

	std::cout << "disparando gerador " << i << std::endl;
	std::cout << "thread id:" << std::this_thread::get_id() << std::endl;

	for (int x = 0; x < 6; x++){     //neste exemplo os geradores criam so 6 carros cada (fixo); alterar isto no modelo do prototipo...
		std::this_thread::sleep_for(std::chrono::seconds(tempo));  //aqui o tempo pode ser substituido por exponencial(tempo)

	    mu.lock();
	     cntr++;
		 placa = cntr;  // o valor da placa é obtido a partir da variavel global cntr; como cntr esta sendo compartilhada entre as threads
	    mu.unlock();	// o acesso a ela deve ser protegido.

		std::cout << "gerador " << i << " criou carro " << placa << " em " << getClock() << std::endl;
		f->insert(new Carro(placa));
	}
}