Esempio n. 1
0
int Game::run()
{
    if (!_state) {
        fprintf(stderr, "No state provided \n");
        return -1;
    }

    if (_failtype < 0)
        return _failtype;

    while(Globals::_running) {
#if defined(SDL_VIDEO)
        while(SDL_PollEvent(&_event)) {
            switch(_event.type) {
                case SDL_QUIT:
                    Globals::quit();
#ifdef DEBUG
                    fprintf(stdout, "Quit pressed\n");
#endif
                    break;
                case SDL_KEYUP:
                    Globals::keys.setKeyState(Keyboard::Key::State::RELEASED, _event.key.keysym.sym);
                    break;
                case SDL_KEYDOWN:
                    Globals::keys.setKeyState(Keyboard::Key::State::PRESSED, _event.key.keysym.sym);
                    break;
                case SDL_MOUSEMOTION:
                    Globals::mouse.setMousePos(_event.motion.x, _event.motion.y);
                    break;
                case SDL_MOUSEBUTTONUP:
                    Globals::mouse.setButtonState(SDL_MOUSEBUTTONUP, _event.button.button);
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    Globals::mouse.setButtonState(SDL_MOUSEBUTTONDOWN, _event.button.button);
                    break;
            }
        }

#elif  defined(X11_VIDEO) && defined(HW_RENDER)
        while(XPending(_GLWin.dpy) > 0)
        {   
            XNextEvent(_GLWin.dpy, &_event);
            switch(_event.type)
            {   
                case Expose:
                    if (_event.xexpose.count != 0)
                        break;

#ifdef DEBUG
                    fprintf(stdout, "Expose\n");
#endif
                    break;
                case ConfigureNotify:
                    if ((_event.xconfigure.width  != (signed) _GLWin.width) ||
                            (_event.xconfigure.height != (signed) _GLWin.height))
                    {   
                        _GLWin.width  = _event.xconfigure.width;
                        _GLWin.height = _event.xconfigure.height;

#ifdef DEBUG
                        fprintf(stdout, "Resize Event\n");
#endif                              
                    }   
                    break;
                case KeyPress:
                    Globals::keys.setKeyState(Keyboard::Key::State::PRESSED, XLookupKeysym(&_event.xkey,0));
                    break;
                case KeyRelease:
                    {
                        KeyCode key = XLookupKeysym(&_event.xkey,0);
                        if(key != 0)
                            Globals::keys.setKeyState(Keyboard::Key::State::RELEASED, key);
                    }
                    break;
                case ClientMessage:
                    if (*XGetAtomName(_GLWin.dpy, _event.xclient.message_type) == *"WM_PROTOCOLS")
                    {   
#ifdef DEBUG
                        fprintf(stdout, "Quit pressed\n");
#endif
                        Globals::quit();
                    }   
                    break;
                default:
                    break;
            }   
        }   
#endif

        if(_state) {
            _state->update();
            _state->render();
        } else {
            fprintf(stderr, "State not found\n");
        }

#if defined(X11_VIDEO) && defined(HW_RENDER)
        if(_GLWin.doublebuffer)
            glXSwapBuffers(_GLWin.dpy, _GLWin.win);
        else
            glFlush();

        glClearColor( (float) RED_FROM_UI32(State::bgColor)   / 255,
                      (float) GREEN_FROM_UI32(State::bgColor) / 255,
                      (float) BLUE_FROM_UI32(State::bgColor)  / 255,
                      (float) ALPHA_FROM_UI32(State::bgColor) / 255);

        glClear(GL_COLOR_BUFFER_BIT);
        glLoadIdentity();
#elif defined(SDL_VIDEO) && defined(HW_RENDER)
        SDL_GL_SwapBuffers();

        glClearColor( (float) RED_FROM_UI32(State::bgColor)   / 255,
                      (float) GREEN_FROM_UI32(State::bgColor) / 255,
                      (float) BLUE_FROM_UI32(State::bgColor)  / 255,
                      (float) ALPHA_FROM_UI32(State::bgColor) / 255);

        glClear(GL_COLOR_BUFFER_BIT);
        glLoadIdentity();
#elif defined(SDL_VIDEO) && defined(SW_RENDER)
        SDL_BlitSurface(Globals::_buffer, 0, _screen, 0);
        SDL_UpdateRect(_screen, 0,0,0,0);
        SDL_FillRect(Globals::_buffer,0, State::bgColor);
#endif

        unsigned int now;
        _frametime = 0;

        do {
            timeb tb;
            ftime( &tb );
            now = tb.millitm + (tb.time & 0xfffff) * 1000;
            _frametime = (now > _lasttime) ? now - _lasttime : 0;
            _lasttime  = (now >= _lasttime) ? _lasttime : now;
        } while(!(_frametime >= minFPS));

        if(_frametime > maxFPS)
            _frametime = maxFPS;

        _timeaccum += _frametime;
        _framecount++;
        _elapsed = (float) _frametime * 0.001f;

        if(_timeaccum >= 1000) {
            Globals::FPS = _frametime;
            _framecount   = 0;
            _timeaccum    = 0;
        }

        Globals::elapsed = _elapsed;
        _lasttime = now;
    }

    return 0;
}
Esempio n. 2
0
void
SMTPMessage::Send()
{
	HandleAddresses();

	AppendToOutbox("From ");
	AppendToOutbox(*itsFrom);
	AppendToOutbox(" ");

	struct timeb tp;
	ftime(&tp);
	JString date(ctime(&(tp.time)));
	AppendToOutbox(date);

	std::istrstream is(date.GetCString(), date.GetLength());
	JString dow;
	JString mon;
	JString day;
	JString rest;
	dow = JReadUntilws(is);
	mon = JReadUntilws(is);
	day = JReadUntilws(is);
	JReadAll(is, &rest);

	AppendToOutbox("Date: ");
	AppendToOutbox(dow);
	AppendToOutbox(", ");
	AppendToOutbox(day);
	AppendToOutbox(" ");
	AppendToOutbox(mon);
	AppendToOutbox(" ");
	AppendToOutbox(rest);

	JString addrStr = itsSMTPServer;
	if (!addrStr.Contains(":"))
		{
		addrStr += ":25";
		}
	ACE_INET_Addr addr(addrStr);

	itsLink = new InetLink;
	assert(itsLink != NULL);

	itsConnector = new INETConnector;
	assert( itsConnector != NULL );

	ACE_Synch_Options options(ACE_Synch_Options::USE_REACTOR, ACE_Time_Value(kMaxWaitSeconds));

	if (itsConnector->connect(itsLink, addr, options) == -1 &&
		jerrno() != EAGAIN)
		{
		JString notice	= "No response from sendmail : Error number ";
		int errNumber	= jerrno();
		notice += JString(errNumber);
		JGetUserNotification()->ReportError(notice);
		itsDeleteTask = new JXTimerTask(1000,kJTrue);
		assert( itsDeleteTask != NULL );
		itsDeleteTask->Start();
		ListenTo(itsDeleteTask);
		Broadcast(SendFailure());
//		itsLink = NULL;
		return;
		}
	itsTimeoutTask = new JXTimerTask(kMaxWaitSeconds * 1000,kJTrue);
	assert( itsTimeoutTask != NULL );
	itsTimeoutTask->Start();
	ListenTo(itsTimeoutTask);
	ClearWhenGoingAway(itsLink, &itsLink);
}
unsigned long XMLPlatformUtils::getCurrentMillis()
{
    timeb aTime;
    ftime(&aTime);
    return (unsigned long)(aTime.time*1000 + aTime.millitm);
}
/**
 * update array with the received data
 */
void MutexKnobData::SetMutexKnobDataReceived(knobData *kData) {
    char units[40];
    char fec[40];
    char dataString[1024];
    double diff;
    struct timeb now;
    QMutexLocker locker(&mutex);
    int index = kData->index;
    memcpy(&KnobData[index].edata, &kData->edata, sizeof(epicsData));

    /*****************************************************************************************/
    // Statistics
    /*****************************************************************************************/

    nbMonitors++;

    // find monitor with highest count since last time
    if((kData->edata.monitorCount-kData->edata.monitorCountPrev) > highestCount) {
        highestCount = kData->edata.monitorCount -kData->edata.monitorCountPrev ;
        highestIndex = index;
    }

    // calculate after 5 seconds our statistics
    ftime(&now);
    diff = ((double) now.time + (double) now.millitm / (double)1000) -
            ((double) monitorTiming.time + (double) monitorTiming.millitm / (double)1000);

    if(diff >= 5.0) {
        ftime(&monitorTiming);
        nbMonitorsPerSecond = (int) (nbMonitors/diff);
        nbMonitors = 0;
        // remember monitor count for all monitors
        for(int i=0; i < GetMutexKnobDataSize(); i++) {
            knobData *kPtr = (knobData*) &KnobData[i];
            if(kPtr->index != -1) kPtr->edata.monitorCountPrev = kPtr->edata.monitorCount;
        }

        highestCountPerSecond = highestCount / diff;
        highestIndexPV = highestIndex;
        highestCount = 0;
        nbDisplayCountPerSecond =  (int) (displayCount/diff);
        displayCount = 0;
    }

    /*****************************************************************************************/

    // direct update without timing

    if(myUpdateType == UpdateDirect) {
        QWidget *dispW = (QWidget*) kData->dispW;
        dataString[0] = '\0';
        strcpy(units, kData->edata.units);
        strcpy(fec, kData->edata.fec);
        int caFieldType= kData->edata.fieldtype;

        if((caFieldType == DBF_STRING || caFieldType == DBF_ENUM || caFieldType == DBF_CHAR) && kData->edata.dataB != (void*) 0) {
            if(kData->edata.dataSize < 1024) {
                memcpy(dataString, (char*) kData->edata.dataB, kData->edata.dataSize);
                dataString[kData->edata.dataSize] = '\0';
            }
        }

        kData->edata.displayCount = kData->edata.monitorCount;
        locker.unlock();
        UpdateWidget(index, dispW, units, fec, dataString, KnobData[index]);
        kData->edata.lastTime = now;
        kData->edata.initialize = false;
        displayCount++;
    }
}
/**
  * timer is running with 50 ms speed
  */
void MutexKnobData::timerEvent(QTimerEvent *)
{
    double diff, repRate;
    char units[40];
    char fec[40];
    char dataString[1024];
    struct timeb now;

    if(blockProcess) return;

    ftime(&now);

    //qDebug() << "============================================";
    for(int i=0; i < GetMutexKnobDataSize(); i++) {
        knobData *kPtr = (knobData*) &KnobData[i];

        if(kPtr->index != -1) {
            diff = ((double) now.time + (double) now.millitm / (double)1000) -
                    ((double) kPtr->edata.lastTime.time + (double) kPtr->edata.lastTime.millitm / (double)1000);
            if(kPtr->edata.repRate < 1) repRate = 1;
            else repRate = kPtr->edata.repRate;
        }

        // update all graphical items for this soft pv when a value changes
        if(kPtr->index != -1 && kPtr->soft && (diff >= (1.0/(double)repRate))) {
            int indx;
            //qDebug() << "I am a soft channel" << kPtr->pv << kPtr->dispName << kPtr->edata.rvalue << kPtr->index;
            // get for this soft pv the index of the corresponding caCalc into the knobData array where the data were updated
            if(getSoftPV(kPtr->pv, &indx, (QWidget*) kPtr->thisW)) {
                // get value from (updated) QMap variable list
                knobData *ptr = (knobData*) &KnobData[indx];
                kPtr->edata.rvalue = ptr->edata.rvalue;
                kPtr->edata.fieldtype = caDOUBLE;
                kPtr->edata.connected = true;
                kPtr->edata.accessW = true;
                kPtr->edata.accessR = true;
                //increase monitor count when value has changed
                if(kPtr->edata.oldsoftvalue != ptr->edata.rvalue) {
                    //qDebug() << kPtr->pv << kPtr->dispName << "will be updated with value=" << ptr->edata.rvalue << "from" << ptr->pv << "index=" << ptr->index << "oldvalue=" << kPtr->edata.oldsoftvalue;
                    kPtr->edata.monitorCount++;
                }

                // when any monitors for calculation increase monitorcount
                QWidget *w1 =  (QWidget*) kPtr->dispW;
                QVariant var = w1->property("MonitorList");
                QVariantList list = var.toList();
                if(list.size() > 0) {
                    int nbMonitors = list.at(0).toInt();
                    if(nbMonitors > 0) {
                        kPtr->edata.monitorCount++;
                    }
                }

                kPtr->edata.oldsoftvalue = ptr->edata.rvalue;
                QWidget *ww = (QWidget *)kPtr->dispW;
                if (caTextEntry *widget = qobject_cast<caTextEntry *>(ww)) {
                    widget->setAccessW(kPtr->edata.accessW);
                }
            }
        }

        // use specified repetition rate (normally 5Hz)
        if( ((kPtr->index != -1) && (kPtr->edata.monitorCount > kPtr->edata.displayCount) && (diff >= (1.0/(double)repRate)))){
            /*
            printf("<%s> index=%d mcount=%d dcount=%d value=%f datasize=%d valuecount=%d\n", kPtr->pv, kPtr->index, kPtr->edata.monitorCount,
                                                                      kPtr->edata.displayCount, kPtr->edata.rvalue,
                                                                      kPtr->edata.dataSize, kPtr->edata.valueCount);
*/
            if((myUpdateType == UpdateTimed) || kPtr->soft) {
                QMutexLocker locker(&mutex);
                int index = kPtr->index;
                QWidget *dispW = (QWidget*) kPtr->dispW;
                dataString[0] = '\0';
                strcpy(units, kPtr->edata.units);
                strcpy(fec, kPtr->edata.fec);
                int caFieldType= kPtr->edata.fieldtype;

                if((caFieldType == DBF_STRING || caFieldType == DBF_ENUM || caFieldType == DBF_CHAR) && kPtr->edata.dataB != (void*) 0) {
                    if(kPtr->edata.dataSize < 1024) {
                        memcpy(dataString, (char*) kPtr->edata.dataB, kPtr->edata.dataSize);
                        dataString[kPtr->edata.dataSize] = '\0';
                    } else {
                        memcpy(dataString, (char*) kPtr->edata.dataB, 1024);
                        dataString[1023] = '\0';
                    }
                }

                kPtr->edata.displayCount = kPtr->edata.monitorCount;
                locker.unlock();
                UpdateWidget(index, dispW, units, fec, dataString, KnobData[index]);
                kPtr->edata.lastTime = now;
                kPtr->edata.initialize = false;
                displayCount++;
            }

        } else if ((kPtr->index != -1)  && (diff >= (1.0/(double)repRate))) {
            if( (!kPtr->edata.connected)) {
                QMutexLocker locker(&mutex);
                bool displayIt = false;
                units[0] = '\0';
                fec[0] = '\0';
                dataString[0] = '\0';
                int index = kPtr->index;
                // brake unconnected displays
                if(kPtr->edata.unconnectCount == 0) {
                    kPtr->edata.displayCount = kPtr->edata.monitorCount;
                    kPtr->edata.lastTime = now;
                    displayIt = true;
                }
                kPtr->edata.unconnectCount++;
                if(kPtr->edata.unconnectCount == 10) kPtr->edata.unconnectCount=0;
                locker.unlock();
                if(displayIt) UpdateWidget(index, (QWidget*) kPtr->dispW, units, fec, dataString, KnobData[index]);
            }
        }
    }
}
Esempio n. 6
0
Uint32 tu_timer::get_ticks()
{
	struct timeb tv;
	ftime(&tv);
	return  (tv.time - s_start_time.time) * 1000 + (tv.millitm - s_start_time.millitm);
}
Esempio n. 7
0
void gettimeofday(struct timeval* t,void* timezone) {
  struct timeb timebuffer;
  ftime( &timebuffer );
  t->tv_sec=timebuffer.time;
  t->tv_usec=1000*timebuffer.millitm;
}
Esempio n. 8
0
ZLTime ZLUnixTimeManager::currentTime() const {
	struct timeb timeB;
	ftime(&timeB);
	return ZLTime(timeB.time, timeB.millitm);
}
Esempio n. 9
0
int main(int argc, char *argv[])   /* Main program */ 
{
	
	int runs;
	sscanf(argv[1],"%d",&runs);
	//scanf("%d",&runs);
	
    /* Local variables */
     REAL *t = (REAL*)malloc(sizeof(REAL));
	 REAL *y/*[4]*/ = (REAL*)malloc(sizeof(REAL)*4);
     int *jt = (int*)malloc(sizeof(int));
     int *neq = (int*)malloc(sizeof(int));
	 int *liw = (int*)malloc(sizeof(int));
	 int *lrw = (int*)malloc(sizeof(int));
     REAL *atol/*[1]*/ = (REAL*)malloc(sizeof(REAL));
     int *itol =(int*) malloc(sizeof(int));
	 int *iopt =(int*) malloc(sizeof(int));
     REAL *rtol = (REAL*)malloc(sizeof(REAL));
     int *iout =(int*) malloc(sizeof(int));
     REAL *tout =(REAL*) malloc(sizeof(REAL));
     int *itask = (int*)malloc(sizeof(int));
	 int *iwork/*[24]*/ =(int*) malloc(sizeof(int)*24);
     REAL *rwork/*[86]*/ = (REAL*)malloc(sizeof(REAL)*86);
	 int *istate = (int*)malloc(sizeof(int));
	struct cuLsodaCommonBlock common;
	struct cuLsodaCommonBlock *Hcommon = &common;
		 int *err = (int*)malloc(sizeof(int));

	/* End Local Block */
	clock_t startTime, endTime;
	double procTime = 0;
	struct timeb bstart,bstop;
	double btime;

	/* End Pointer Block */
	
	
	
	/* Method instantiations for Derivative and Jacobian functions to send to template */
	benchFex fex;
	myJex jex;

	
	/* Assignment of initial values to locals */
    *neq = 4;
	y[0] = (REAL)0.;
    y[1] = (REAL)0.;
    y[2] = (REAL)0.;
	y[3] = (REAL)0.;
    *t = (REAL)0.;
//	printf("\n\n\n\n\n\nPlease enter the desired output time: ");
    REAL outtime = 10000;
	//scanf("%lf",&outtime);
	//printf("%f\n",outtime);
	*tout = (REAL) outtime;
//	*tout = (REAL)1000000.;

	*itol = 1;
    *rtol = (REAL)0.;
    *atol = (REAL)1.e-5;
    *itask = 1;
    *istate = 1;
    *iopt = 1;
	int mxstpH;
	//printf("Please enter the desired Maximum Step number: ");
	//scanf("%d",&mxstpH);
	mxstpH = 200000;
	iwork[5] = mxstpH;
    *lrw = 86;
    *liw = 24;
    *jt = 2;
	cuLsodaCommonBlockInit(Hcommon);
	*err = -1;
	
		
	int error = -1;
	int error2 = -1;
	

	startTime = clock();
	ftime(&bstart);
	for (*iout = 0; *iout < runs; ++*iout) 
	{
			y[0] = (REAL)0.;
		y[1] = (REAL)0.;
		y[2] = (REAL)0.;
		y[3] = (REAL)0.;
		*t = (REAL)0.;
		//	printf("\n\n\n\n\n\nPlease enter the desired output time: ");
		
		*itask = 1;
		*istate = 1;
		*iopt = 1;
		iwork[5] = mxstpH;
		//printf("Calling Kernel Sanders\n");
		Sanders(fex, neq, y, t, tout, itol, rtol, atol, itask, istate, iopt, rwork, lrw, iwork, liw, jex, jt, Hcommon, err);

			//float elapsedTime;
		
	
		
				

	//	printf("At t =\t%- #12.2ey = %- #16.12e\t%- #16.12e\t%- #16.12e\t%- #16.12e\nError = %d\t Error2 = %d\t err = %d\nElapsed Time = %f seconds\n", *t, y[0], y[1], y[2], y[3],error,error2,*err,elapsedTime/1000.);
	/*	printf("\tCM_conit = %f\n",Hcommon->CM_conit);
		printf("\tCM_crate = %f\n",Hcommon->CM_crate);
		printf("\tCM_ccmax = %f\n",Hcommon->CM_ccmax);
		printf("\tCM_el0 = %f\n",Hcommon->CM_el0);
		printf("\tCM_h__ = %f\n",Hcommon->CM_h__);
		printf("\tCM_hmin = %f\n",Hcommon->CM_hmin);
		printf("\tCM_hmxi = %f\n",Hcommon->CM_hmxi);
		printf("\tCM_hu = %f\n",Hcommon->CM_hu);
		printf("\tCM_rc = %f\n",Hcommon->CM_rc);
		printf("\tCM_tn = %f\n",Hcommon->CM_tn);
		printf("\tCM_uround = %f\n",Hcommon->CM_uround);
		printf("\tCM_pdest = %f\n",Hcommon->CM_pdest);
		printf("\tCM_pdlast = %f\n",Hcommon->CM_pdlast);
		printf("\tCM_ratio = %f\n",Hcommon->CM_ratio);
		printf("\tCM_hold = %f\n",Hcommon->CM_hold);
		printf("\tCM_rmax = %f\n",Hcommon->CM_rmax);
		printf("\tCM_tsw = %f\n",Hcommon->CM_tsw);
		printf("\tCM_pdnorm = %f\n",Hcommon->CM_pdnorm);*/
		
		//error = error2 = -1;

		if (istate < 0) {
			printf( "STOP istate is < 0\n\n\n\n");
		}
		
    }
 	//printf("Number of Steps:  %i\nNo. f-s: %i\nNo. J-s = %i\nMethod Last Used = %i\nLast switch was at t = %g\n",iwork[10],iwork[11],iwork[12],iwork[18],rwork[14]);
	endTime= clock();
	ftime(&bstop);
	btime=(double)(bstop.time-bstart.time)+0.001*((bstop.millitm-bstart.millitm));
	procTime = ((double)endTime -(double)startTime)/(double)CLOCKS_PER_SEC;
L80:
 
	printf("runs\t%d\ttime\t%- #12.2ey\t%- #16.12e\t%- #16.12e\t%- #16.12e\t%- #16.12e\tElTime\t%f\t%f\n",runs, *(t), y[0], y[1], y[2], y[3], procTime,btime );
	
	return 0;
} /* MAIN__ */
Esempio n. 10
0
/**
 * Log a message.  If possible, all messages should be indexed by message number, and
 * the use of the format string should be minimized or negated altogether.  If format is
 * provided, the message number is only used as a message label.
 * @param log_level the log level of the message
 * @param msgno the id of the message to use if the format string is NULL
 * @param aFormat the printf format string to be used if the message id does not exist
 * @param ... the printf inserts
 */
void Log(int log_level, int msgno, char* format, ...)
{
	int islogmsg = 1;
	char* temp = NULL;
	static char msg_buf[256];

	if (log_level < LOG_CONFIG)
		islogmsg = 0;

#if defined(HIGH_PERFORMANCE)
	if (!islogmsg)
#else
	if (!islogmsg && log_level < trace_settings.trace_level)
#endif
		return;

	if (islogmsg &&	log_level < trace_settings.log_level)
		return;

	if (format == NULL && (temp = Messages_get(msgno, log_level)) != NULL)
		format = temp;

	if (!islogmsg)
	{
		static char trace_msg_buf[256];
		va_list args;

		va_start(args, format);
		vsnprintf(trace_msg_buf, sizeof(trace_msg_buf), format, args);
		Log_trace(log_level, trace_msg_buf);
		va_end(args);
		return;
	}

	if (Log_recurse_flag == 0)
	{
		struct tm *timeinfo;
		char level_char = ' ';
		int buf_pos = 31;
		va_list args;

#if defined(GETTIMEOFDAY)
		gettimeofday(&ts, NULL);
		timeinfo = localtime(&ts.tv_sec);
#else
		ftime(&ts);
		timeinfo = localtime(&ts.time);
#endif
		strftime(&msg_buf[7], 80, "%Y%m%d %H%M%S ", timeinfo);
#if defined(GETTIMEOFDAY)
		sprintf(&msg_buf[22], ".%.3lu ", ts.tv_usec / 1000L);
#else
		sprintf(&msg_buf[22], ".%.3hu ", ts.millitm);
#endif
		buf_pos = 27;

#if defined(GETTIMEOFDAY)
		if (ts.tv_sec == last_ts.tv_sec && ts.tv_usec == last_ts.tv_usec)
#else
		if (ts.time == last_ts.time && ts.millitm == last_ts.millitm)
#endif
			++sametime_count; /* this message has the same timestamp as the last, so increase the sequence no */
		else
		{
			sametime_count = 0;
			last_ts = ts;
		}
		sprintf(msg_buf, "(%.4d)", sametime_count);
		msg_buf[6] = ' ';

		level_char = "     CDIAWESF"[log_level];
		sprintf(&msg_buf[buf_pos], "%s%.4d%c ", MSG_PREFIX, msgno, level_char);
		buf_pos += 11;

		va_start(args, format);
		vsnprintf(&msg_buf[buf_pos], sizeof(msg_buf)-buf_pos, format, args);
		va_end(args);

		if (log_level >= LOG_ERROR)
		{
			char* filename = NULL;
			Log_recurse_flag = 1;
			filename = Broker_recordFFDC(&msg_buf[7]);
			Log_recurse_flag = 0;
			snprintf(&msg_buf[buf_pos], sizeof(msg_buf)-buf_pos, Messages_get(13, LOG_WARN), filename);
		}

		addToBuffer(log_buffer, msg_buf);
#if !defined(WIN32)
		if (trace_settings.isdaemon)
		{
			static char priorities[] = { 7, 7, 7, 7, 6, 6, 5, 5, 4, 3, 1, 0};
			syslog(priorities[log_level], "%s", &msg_buf[22]);
		}
		else
		{
#endif
			printf("%s\n", &msg_buf[7]);
			fflush(stdout);
#if !defined(WIN32)
		}
#endif
		if (Log_publishFlag)
		{
			#define MAX_LOG_TOPIC_NAME_LEN 25
			static char topic_buf[MAX_LOG_TOPIC_NAME_LEN];
			sprintf(topic_buf, "$SYS/broker/log/%c/%.4d", level_char, msgno);
			Log_recurse_flag = 1;
			Log_Publish(topic_buf, &msg_buf[7]);
			Log_recurse_flag = 0;
		}
	}

	if (log_level == LOG_FATAL)
		exit(-1);
}
Esempio n. 11
0
int gettimeofday(struct timeval* tp, int* /*tz*/) {
  static LARGE_INTEGER tickFrequency, epochOffset;

  static Boolean isInitialized = False;

  LARGE_INTEGER tickNow;

#if !defined(_WIN32_WCE)
  QueryPerformanceCounter(&tickNow);
#else
  tickNow.QuadPart = GetTickCount();
#endif
 
  if (!isInitialized) {
    if(1 == InterlockedIncrement(&initializeLock_gettimeofday)) {
#if !defined(_WIN32_WCE)
      // For our first call, use "ftime()", so that we get a time with a proper epoch.
      // For subsequent calls, use "QueryPerformanceCount()", because it's more fine-grain.
      struct timeb tb;
      ftime(&tb);
      tp->tv_sec = tb.time;
      tp->tv_usec = 1000*tb.millitm;

      // Also get our counter frequency:
      QueryPerformanceFrequency(&tickFrequency);
#else
      /* FILETIME of Jan 1 1970 00:00:00. */
      const LONGLONG epoch = 116444736000000000LL;
      FILETIME fileTime;
      LARGE_INTEGER time;
      GetSystemTimeAsFileTime(&fileTime);

      time.HighPart = fileTime.dwHighDateTime;
      time.LowPart = fileTime.dwLowDateTime;

      // convert to from 100ns time to unix timestamp in seconds, 1000*1000*10
      tp->tv_sec = (long)((time.QuadPart - epoch) / 10000000L);

      /*
        GetSystemTimeAsFileTime has just a seconds resolution,
        thats why wince-version of gettimeofday is not 100% accurate, usec accuracy would be calculated like this:
        // convert 100 nanoseconds to usec
        tp->tv_usec= (long)((time.QuadPart - epoch)%10000000L) / 10L;
      */
      tp->tv_usec = 0;

      // resolution of GetTickCounter() is always milliseconds
      tickFrequency.QuadPart = 1000;
#endif     
      // compute an offset to add to subsequent counter times, so we get a proper epoch:
      epochOffset.QuadPart
          = tp->tv_sec * tickFrequency.QuadPart + (tp->tv_usec * tickFrequency.QuadPart) / 1000000L - tickNow.QuadPart;
      
      // next caller can use ticks for time calculation
      isInitialized = True; 
      return 0;
    } else {
        InterlockedDecrement(&initializeLock_gettimeofday);
        // wait until first caller has initialized static values
        while(!isInitialized){
          Sleep(1);
        }
    }
  }

  // adjust our tick count so that we get a proper epoch:
  tickNow.QuadPart += epochOffset.QuadPart;

  tp->tv_sec =  (long)(tickNow.QuadPart / tickFrequency.QuadPart);
  tp->tv_usec = (long)(((tickNow.QuadPart % tickFrequency.QuadPart) * 1000000L) / tickFrequency.QuadPart);

  return 0;
}
Esempio n. 12
0
void CStereoMatcher::OptBP()
{
  CShape sh = m_cost.Shape();

  int H = sh.height;
  int W = sh.width;

  const int numRows = H,
    numCols = W,
    numNodes = W *H;

  OneNodeCluster *nodeArray;
  const int numStates = m_disp_n;
    FLOATTYPE alpha = 0.95;

  unsigned int totalMem = 0;

  nodeArray = new OneNodeCluster[numNodes];
  FLOATTYPE *oneNodeMsgArray = new FLOATTYPE[numNodes * 8 * numStates];
  FLOATTYPE *oneNodeLocalEv = new FLOATTYPE[numStates * numNodes],
    *currLocalEvPtr = oneNodeLocalEv;

  totalMem += sizeof(OneNodeCluster) * numNodes;
  totalMem += sizeof(FLOATTYPE) * numNodes * 8 * numStates;
  totalMem += sizeof(FLOATTYPE) * numNodes * numStates;
  
  OneNodeCluster::numStates = numStates;
  TwoNodeCluster::numStates = numStates;
  printf("NumStates: %d\n",nodeArray[0].numStates);

  for (int i = 0; i < numNodes * 8 * numStates; i++)
  {
    oneNodeMsgArray[i] = 1.0f/numStates;
  }

  initOneNodeMsgMem(nodeArray,oneNodeMsgArray,numNodes, numStates);

  TwoNodeCluster dummyNode;
  FLOATTYPE dummyMessages[numStates * numStates*4];

  for(int i = 0; i < numStates * numStates*4; i++)
    dummyMessages[i] = 1.0f;

  
  
  printf("Msg Space Allocated and Initialized\n");

  CShape sh2 = m_cost.Shape();
  printf("%d %d\n",m_disp_n, sh2.nBands);
    for(int m = 0; m < numRows; m++)
    {
      float* smoothcost_vert = &m_smooth.Pixel(0, m, 0); // band 1 is horizontal cost
      float* smoothcost_horz = &m_smooth.Pixel(0, m, 1); // band 1 is horizontal cost
      float* local_cost = &m_cost.Pixel(0, m, 0);
    
      for(int n = 0; n < numCols; n++)
      {
	const double div_factor = 50;
        const double vsmooth_cost = exp(-1*smoothcost_vert[0]/div_factor),
	  hsmooth_cost = exp(-1*smoothcost_horz[0]/div_factor);
	

        const int cind = m * numCols + n;

        nodeArray[cind].localEv = currLocalEvPtr;
        currLocalEvPtr += numStates;
        for (int i = 0; i < m_disp_n; i++)
        {
	  nodeArray[cind].localEv[i] = exp(-1 *local_cost[i]/div_factor);
        }

        nodeArray[cind].psiData_pottsSameProb[OneNodeCluster::UP]=1;
        nodeArray[cind].psiData_pottsSameProb[OneNodeCluster::DOWN]=1;
        nodeArray[cind].psiData_pottsSameProb[OneNodeCluster::LEFT]=1;
        nodeArray[cind].psiData_pottsSameProb[OneNodeCluster::RIGHT]=1;

        if (n == 0)
	  nodeArray[cind].psiData_pottsDiffProb[OneNodeCluster::LEFT] = 1;

        if (n < numCols-1)
        {
	  nodeArray[cind+1].psiData_pottsDiffProb[OneNodeCluster::LEFT] = hsmooth_cost;
	  nodeArray[cind].psiData_pottsDiffProb[OneNodeCluster::RIGHT] = hsmooth_cost;
	}
        else
        {
	  nodeArray[cind].psiData_pottsDiffProb[OneNodeCluster::RIGHT]=1;
        }

        if (m == 0)
	  nodeArray[cind].psiData_pottsDiffProb[OneNodeCluster::UP] = 1;

        if(m != numRows -1)
	{	
	  nodeArray[cind+numCols].psiData_pottsDiffProb[OneNodeCluster::UP] = vsmooth_cost;
	  nodeArray[cind].psiData_pottsDiffProb[OneNodeCluster::DOWN] = vsmooth_cost;
	}
        else
        {
	  nodeArray[cind].psiData_pottsDiffProb[OneNodeCluster::DOWN]=1;
        }


        smoothcost_horz += 2;
        smoothcost_vert += 2;
        local_cost += m_disp_n;
      }
    }
  
    int numIter;
    //Initialization Completed Time for the good stuff
    
    numIter = 50;
    printf("Structures Initialized\n");
    
    int iter = 0;
    
    int beliefIm[H * W];
    for (int i = 0; i < H * W; i++)
      beliefIm[i] = 0;

    while (iter < numIter)//( !converged)
    {

      printf("Iter %03d\n",iter);
      struct timeb start, endtime;
      ftime(&start);
      for (int m = 0; m < numRows; m++)
      {
	passOneNodeMsgsLeft(&nodeArray[m *numCols], numCols, 0,0,dummyNode,alpha);
	passOneNodeMsgsRight(&nodeArray[m *numCols], numCols, 0,0,dummyNode,alpha);
      }
      
      for(int n = 0; n < numCols; n++)
      {
	passOneNodeMsgsDown(nodeArray,(TwoNodeCluster **)0,dummyNode,n,numRows,numCols,alpha);

	passOneNodeMsgsUp(nodeArray,(TwoNodeCluster **)0,dummyNode,n,numRows,numCols,alpha);
      }
      ftime(&endtime);
      float etime = (float)(endtime.time - start.time) + 0.001 * (float) (endtime.millitm - start.millitm);
      printf ("%f Seconds ",etime);

      float tmpBeliefVec[numStates];
      float *beliefPtr;
    
      for(int m = 0; m < numRows; m++)
      {
	int *disp = &m_disparity.Pixel(0, m, 0);    
      
	for(int n = 0; n < numCols; n++)
	{
	  double best_prob = 0;
	  int best_d = 0;
	  
	  nodeArray[m * numCols + n].getBelief(tmpBeliefVec);
	  beliefPtr =tmpBeliefVec;
	  for(int j =0; j <numStates;j++)
	  {
	    
	    if (*beliefPtr > best_prob)
	    {
	      best_prob = *beliefPtr;
	      best_d = j;
	    }
	    beliefPtr++;
	  }
	  
	  disp[n] = best_d;
	}
      }
      float locEn, smoothEn;
      ComputeEnergy(m_cost, m_smooth, m_disparity, locEn, smoothEn);
      printf("Energy:%.2f Local %.2f Smooth: %.2f\n",locEn+smoothEn, locEn,smoothEn);
      iter++;
    }

    float tmpBeliefVec[numStates];
    float *beliefPtr;
    
    for(int m = 0; m < numRows; m++)
    {
      int *disp = &m_disparity.Pixel(0, m, 0);    
      
      for(int n = 0; n < numCols; n++)
      {
	double best_prob = 0;
	int best_d = 0;
	
	nodeArray[m * numCols + n].getBelief(tmpBeliefVec);
	beliefPtr =tmpBeliefVec;
	for(int j =0; j <numStates;j++)
	{
	  
	  if (*beliefPtr > best_prob)
	  {
	    best_prob = *beliefPtr;
	    best_d = j;
	  }
	  beliefPtr++;
	}
	
	disp[n] = best_d;
      }
      
    }
    
  
    
    printf("\nTotalMem:%ud\n",totalMem/1024/1024);
    delete nodeArray;
    delete oneNodeMsgArray;
    delete oneNodeLocalEv;

}
Esempio n. 13
0
void build_connectivity_graph( void )

{

  int i, j, k, l, n_op, n_ef, na, nd, ef, ef_, m, l_;
  Action *a;
  int *same_effects, sn;
  Bool *had_effects;
  ActionEffect *e, *e_, *e__;

  struct timeb tp;

  ftime( &tp );
  srandom( tp.millitm );

  gnum_ft_conn = gnum_relevant_facts;
  gnum_op_conn = gnum_actions;
  gft_conn = ( FtConn * ) calloc( gnum_ft_conn, sizeof( FtConn ) );
  gop_conn = ( OpConn * ) calloc( gnum_op_conn, sizeof( OpConn ) );
  gef_conn = ( EfConn * ) calloc( lnum_effects, sizeof( EfConn ) );
  gnum_ef_conn = 0;

  same_effects = ( int * ) calloc( lnum_effects, sizeof( int ) );
  had_effects = ( Bool * ) calloc( lnum_effects, sizeof( Bool ) );

  for ( i = 0; i < gnum_ft_conn; i++ ) {
    gft_conn[i].num_PC = 0;
    gft_conn[i].num_A = 0;
    gft_conn[i].num_D = 0;

    gft_conn[i].rand = random() % BIG_INT;
  }

  for ( i = 0; i < gnum_op_conn; i++ ) {
    gop_conn[i].num_E = 0;
  }

  for ( i = 0; i < lnum_effects; i++ ) {
    gef_conn[i].num_PC = 0;
    gef_conn[i].num_A = 0;
    gef_conn[i].num_D = 0;
    gef_conn[i].num_I = 0;

    gef_conn[i].removed = FALSE;
  }


  n_op = 0;
  n_ef = 0;
  for ( a = gactions; a; a = a->next ) {

    gop_conn[n_op].action = a;

    gop_conn[n_op].E = ( int * ) calloc( a->num_effects, sizeof( int ) );
    for ( i = 0; i < a->num_effects; i++ ) {
      had_effects[i] = FALSE;
    }
    for ( i = 0; i < a->num_effects; i++ ) {
      if ( had_effects[i] ) {
	continue;
      }
      had_effects[i] = TRUE;
      e = &(a->effects[i]);
      gop_conn[n_op].E[gop_conn[n_op].num_E++] = n_ef;
      gef_conn[n_ef].op = n_op;

      gef_conn[n_ef].PC = ( int * ) 
	calloc( e->num_conditions + a->num_preconds, sizeof( int ) );
      for ( j = 0; j < a->num_preconds; j++ ) {
	for ( k = 0; k < gef_conn[n_ef].num_PC; k++ ) {
	  if ( gef_conn[n_ef].PC[k] == a->preconds[j] ) break;
	}
	if ( k < gef_conn[n_ef].num_PC ) continue;
	gef_conn[n_ef].PC[gef_conn[n_ef].num_PC++] = a->preconds[j];
      }
      for ( j = 0; j < e->num_conditions; j++ ) {
	for ( k = 0; k < gef_conn[n_ef].num_PC; k++ ) {
	  if ( gef_conn[n_ef].PC[k] == e->conditions[j] ) break;
	}
	if ( k < gef_conn[n_ef].num_PC ) continue;
	gef_conn[n_ef].PC[gef_conn[n_ef].num_PC++] = e->conditions[j];
      }

      sn = 0;
      for ( j = i + 1; j < a->num_effects; j++ ) {
	if ( had_effects[j] ) {
	  continue;
	}
	e_ = &(a->effects[j]);
	/* check conditions
	 */
	for ( k = 0; k < e_->num_conditions; k++ ) {
	  for ( l = 0; l < e->num_conditions; l++ ) {
	    if ( e_->conditions[k] == e->conditions[l] ) {
	      break;
	    }
	  }
	  if ( l == e->num_conditions ) {
	    break;
	  }
	}
	if ( k < e_->num_conditions ) {
	  continue;
	}
	if ( e->num_conditions == e_->num_conditions ) {
	  same_effects[sn++] = j;
	}
      }

      na = e->num_adds;
      nd = e->num_dels;
      for ( j = 0; j < sn; j++ ) {
	na += a->effects[same_effects[j]].num_adds;
	nd += a->effects[same_effects[j]].num_dels;
      }
      gef_conn[n_ef].A = ( int * ) calloc( na, sizeof( int ) );
      gef_conn[n_ef].D = ( int * ) calloc( nd, sizeof( int ) );
      for ( j = 0; j < e->num_adds; j++ ) {
	for ( k = 0; k < gef_conn[n_ef].num_A; k++ ) {
	  if ( gef_conn[n_ef].A[k] == e->adds[j] ) break;
	}
	if ( k < gef_conn[n_ef].num_A ) continue;
	/* exclude already true adds
	 */
	for ( k = 0; k < gef_conn[n_ef].num_PC; k++ ) {
	  if ( gef_conn[n_ef].PC[k] == e->adds[j] ) break;
	}
	if ( k < gef_conn[n_ef].num_PC ) continue;
	gef_conn[n_ef].A[gef_conn[n_ef].num_A++] = e->adds[j];
      }
      for ( j = 0; j < e->num_dels; j++ ) {
	for ( k = 0; k < gef_conn[n_ef].num_D; k++ ) {
	  if ( gef_conn[n_ef].D[k] == e->dels[j] ) break;
	}
	if ( k < gef_conn[n_ef].num_D ) continue;
	/* exclude re-added dels; check against *all*
	 * adds to be integrated.
	 */
	for ( k = 0; k < e->num_adds; k++ ) {
	  if ( e->adds[k] == e->dels[j] ) break;
	}
	if ( k < e->num_adds ) continue;
	for ( l = 0; l < sn; l++ ) {
	  e_ = &(a->effects[same_effects[l]]);
	  for ( k = 0; k < e_->num_adds; k++ ) {
	    if ( e_->adds[k] == e->dels[j] ) break;
	  }
	  if ( k < e_->num_adds ) break;
	}
	if ( l < sn ) continue;
	gef_conn[n_ef].D[gef_conn[n_ef].num_D++] = e->dels[j];
      }
      for ( j = 0; j < sn; j++ ) {
	e_ = &(a->effects[same_effects[j]]);
	for ( l = 0; l < e_->num_adds; l++ ) {
	  for ( k = 0; k < gef_conn[n_ef].num_A; k++ ) {
	    if ( gef_conn[n_ef].A[k] == e_->adds[l] ) break;
	  }
	  if ( k < gef_conn[n_ef].num_A ) continue;
	  for ( k = 0; k < gef_conn[n_ef].num_PC; k++ ) {
	    if ( gef_conn[n_ef].PC[k] == e_->adds[l] ) break;
	  }
	  if ( k < gef_conn[n_ef].num_PC ) continue;
	  gef_conn[n_ef].A[gef_conn[n_ef].num_A++] = e_->adds[l];
	}
	for ( l = 0; l < e_->num_dels; l++ ) {
	  for ( k = 0; k < gef_conn[n_ef].num_D; k++ ) {
	    if ( gef_conn[n_ef].D[k] == e_->dels[l] ) break;
	  }
	  if ( k < gef_conn[n_ef].num_D ) continue;
	  /* exclude re-added dels; check against *all*
	   * adds to be integrated.
	   */
	  for ( k = 0; k < e->num_adds; k++ ) {
	    if ( e->adds[k] == e_->dels[l] ) break;
	  }
	  if ( k < e->num_adds ) continue;
	  for ( l_ = 0; l_ < sn; l_++ ) {
	    e__ = &(a->effects[same_effects[l_]]);
	    for ( k = 0; k < e__->num_adds; k++ ) {
	      if ( e__->adds[k] == e_->dels[l] ) break;
	    }
	    if ( k < e__->num_adds ) break;
	  }
	  if ( l_ < sn ) continue;
	  gef_conn[n_ef].D[gef_conn[n_ef].num_D++] = e_->dels[l];
	}
      }
      for ( j = 0; j < sn; j++ ) {
	had_effects[same_effects[j]] = TRUE;
      }
      
      n_ef++;
      gnum_ef_conn++;
    }/* ende all a->effects */


    if ( gop_conn[n_op].num_E >= 1 ) {
      /* CHECK EMPTY EFFECTS!
       *
       * two step process --- first, remove all effects that are entirely empty.
       *                      second, check if all remaining effects are illegal
       *                      or only delete:
       *                      in that case, the op will never do any good so we 
       *                      remove all its effects.
       */
      i = 0;
      while ( i < gop_conn[n_op].num_E ) {
	if ( gef_conn[gop_conn[n_op].E[i]].num_A != 0 ||
	     gef_conn[gop_conn[n_op].E[i]].num_D != 0 ) {
	  i++;
	  continue;
	}
	/* we keep it in the gef_conn (seems easier), 
	 * but mark it as removed, which will exclude it from everything.
	 */
	gef_conn[gop_conn[n_op].E[i]].removed = TRUE;
	for ( j = i; j < gop_conn[n_op].num_E - 1; j++ ) {
	  gop_conn[n_op].E[j] = gop_conn[n_op].E[j+1];
	}
	gop_conn[n_op].num_E--;
      }

      m = 0;
      for ( i = 0; i < gop_conn[n_op].num_E; i++ ) {
	if ( gef_conn[gop_conn[n_op].E[i]].num_A == 0 ) {
	  m++;
	}
      }
      if ( m == gop_conn[n_op].num_E ) {
	/* all remaining effects solely-deleters.
	 */
	for ( i = 0; i < gop_conn[n_op].num_E; i++ ) {
	  gef_conn[gop_conn[n_op].E[i]].removed = TRUE;
	}
	gop_conn[n_op].num_E = 0;
      }
    }

    /* setup implied effects info
     */
    if ( gop_conn[n_op].num_E > 1 ) {
      for ( i = 0; i < gop_conn[n_op].num_E; i++ ) {
	ef = gop_conn[n_op].E[i];
	gef_conn[ef].I = ( int * ) calloc( gop_conn[n_op].num_E, sizeof( int ) );
	gef_conn[ef].num_I = 0;
      }    
      for ( i = 0; i < gop_conn[n_op].num_E - 1; i++ ) {
	ef = gop_conn[n_op].E[i];
	for ( j = i+1; j < gop_conn[n_op].num_E; j++ ) {
	  ef_ = gop_conn[n_op].E[j];
	  /* ef ==> ef_ ? */
	  for ( k = 0; k < gef_conn[ef_].num_PC; k++ ) {
	    for ( l = 0; l < gef_conn[ef].num_PC; l++ ) {
	      if ( gef_conn[ef].PC[l] == gef_conn[ef_].PC[k] ) break;
	    }
	    if ( l == gef_conn[ef].num_PC ) break;
	  }
	  if ( k == gef_conn[ef_].num_PC ) {
	    gef_conn[ef].I[gef_conn[ef].num_I++] = ef_;
	  }
	  /* j ==> i ? */
	  for ( k = 0; k < gef_conn[ef].num_PC; k++ ) {
	    for ( l = 0; l < gef_conn[ef_].num_PC; l++ ) {
	      if ( gef_conn[ef_].PC[l] == gef_conn[ef].PC[k] ) break;
	    }
	    if ( l == gef_conn[ef_].num_PC ) break;
	  }
	  if ( k == gef_conn[ef].num_PC ) {
	    gef_conn[ef_].I[gef_conn[ef_].num_I++] = ef;
	  }
	}
      }
    }

    /* first sweep: only count the space we need for the fact arrays !
     */
    if ( gop_conn[n_op].num_E > 0 ) {
      for ( i = 0; i < gop_conn[n_op].num_E; i++ ) {
	ef = gop_conn[n_op].E[i];
	for ( j = 0; j < gef_conn[ef].num_PC; j++ ) {
	  gft_conn[gef_conn[ef].PC[j]].num_PC++;
	}
 	for ( j = 0; j < gef_conn[ef].num_A; j++ ) {
	  gft_conn[gef_conn[ef].A[j]].num_A++;
	}
	for ( j = 0; j < gef_conn[ef].num_D; j++ ) {
	  gft_conn[gef_conn[ef].D[j]].num_D++;
	}
      }
    }

    n_op++;
  }

  for ( i = 0; i < gnum_ft_conn; i++ ) {
    if ( gft_conn[i].num_PC > 0 ) {
      gft_conn[i].PC = ( int * ) calloc( gft_conn[i].num_PC, sizeof( int ) );
    }
    gft_conn[i].num_PC = 0;
    if ( gft_conn[i].num_A > 0 ) {
      gft_conn[i].A = ( int * ) calloc( gft_conn[i].num_A, sizeof( int ) );
    }
    gft_conn[i].num_A = 0;
    if ( gft_conn[i].num_D > 0 ) {
      gft_conn[i].D = ( int * ) calloc( gft_conn[i].num_D, sizeof( int ) );
    }
    gft_conn[i].num_D = 0;

    gft_conn[i].is_global_goal = FALSE;
  }
  for ( i = 0; i < ggoal_state.num_F; i++ ) {
    gft_conn[ggoal_state.F[i]].is_global_goal = TRUE;
  }

  for ( i = 0; i < gnum_ef_conn; i++ ) {
    if ( gef_conn[i].removed ) continue;
    for ( j = 0; j < gef_conn[i].num_PC; j++ ) {
      gft_conn[gef_conn[i].PC[j]].PC[gft_conn[gef_conn[i].PC[j]].num_PC++] = i;
    }
    for ( j = 0; j < gef_conn[i].num_A; j++ ) {
      gft_conn[gef_conn[i].A[j]].A[gft_conn[gef_conn[i].A[j]].num_A++] = i;
    }
    for ( j = 0; j < gef_conn[i].num_D; j++ ) {
      gft_conn[gef_conn[i].D[j]].D[gft_conn[gef_conn[i].D[j]].num_D++] = i;
    }
  }

  free( same_effects );
  free( had_effects );

  if ( gcmd_line.display_info == 121 ) {
    printf("\n\ncreated connectivity graph as follows:");

    printf("\n\n------------------OP ARRAY:-----------------------");
    for ( i = 0; i < gnum_op_conn; i++ ) {
      printf("\n\nOP: ");
      print_op_name( i );
      printf("\n----------EFFS:");
      for ( j = 0; j < gop_conn[i].num_E; j++ ) {
	printf("\neffect %d", gop_conn[i].E[j]);
      }
    }
    
    printf("\n\n-------------------EFFECT ARRAY:----------------------");
    for ( i = 0; i < gnum_ef_conn; i++ ) {
      printf("\n\neffect %d of op %d: ", i, gef_conn[i].op);
      print_op_name( gef_conn[i].op );
      if ( gef_conn[i].removed ) {
	printf(" --- REMOVED ");
	continue;
      }
      printf("\n----------PCS:");
      for ( j = 0; j < gef_conn[i].num_PC; j++ ) {
	printf("\n");
	print_ft_name( gef_conn[i].PC[j] );
      }
      printf("\n----------ADDS:");
      for ( j = 0; j < gef_conn[i].num_A; j++ ) {
	printf("\n");
	print_ft_name( gef_conn[i].A[j] );
      }
      printf("\n----------DELS:");
      for ( j = 0; j < gef_conn[i].num_D; j++ ) {
	printf("\n");
	print_ft_name( gef_conn[i].D[j] );
      }
      printf("\n----------IMPLIEDS:");
      for ( j = 0; j < gef_conn[i].num_I; j++ ) {
	printf("\nimplied effect %d of op %d: ", 
	       gef_conn[i].I[j], gef_conn[gef_conn[i].I[j]].op);
	print_op_name( gef_conn[gef_conn[i].I[j]].op );
      }
    }
    
    printf("\n\n----------------------FT ARRAY:-----------------------------");
    for ( i = 0; i < gnum_ft_conn; i++ ) {
      printf("\n\nFT: ");
      print_ft_name( i );
      printf(" rand: %d", gft_conn[i].rand);
      printf("\n----------PRE COND OF:");
      for ( j = 0; j < gft_conn[i].num_PC; j++ ) {
	printf("\neffect %d", gft_conn[i].PC[j]);
      }
      printf("\n----------ADD BY:");
      for ( j = 0; j < gft_conn[i].num_A; j++ ) {
	printf("\neffect %d", gft_conn[i].A[j]);
      }
      printf("\n----------DEL BY:");
      for ( j = 0; j < gft_conn[i].num_D; j++ ) {
	printf("\neffect %d", gft_conn[i].D[j]);
      }
    }
  }
    
}
// get the system time right now
long long getSystemTime() 
{
        struct timeb t;
        ftime(&t);
        return 1000 * t.time + t.millitm;
}
Esempio n. 15
0
//
//=========================================================================
//
void modesInit(void) {
    int i, q;

    pthread_mutex_init(&Modes.data_mutex,NULL);
    pthread_cond_init(&Modes.data_cond,NULL);

    // Allocate the various buffers used by Modes
    if ( ((Modes.icao_cache = (uint32_t *) malloc(sizeof(uint32_t) * MODES_ICAO_CACHE_LEN * 2)                  ) == NULL) ||
         ((Modes.pFileData  = (uint16_t *) malloc(MODES_ASYNC_BUF_SIZE)                                         ) == NULL) ||
         ((Modes.magnitude  = (uint16_t *) malloc(MODES_ASYNC_BUF_SIZE+MODES_PREAMBLE_SIZE+MODES_LONG_MSG_SIZE) ) == NULL) ||
         ((Modes.maglut     = (uint16_t *) malloc(sizeof(uint16_t) * 256 * 256)                                 ) == NULL) ||
         ((Modes.beastOut   = (char     *) malloc(MODES_RAWOUT_BUF_SIZE)                                        ) == NULL) ||
         ((Modes.rawOut     = (char     *) malloc(MODES_RAWOUT_BUF_SIZE)                                        ) == NULL) ) 
    {
        fprintf(stderr, "Out of memory allocating data buffer.\n");
        exit(1);
    }

    // Clear the buffers that have just been allocated, just in-case
    memset(Modes.icao_cache, 0,   sizeof(uint32_t) * MODES_ICAO_CACHE_LEN * 2);
    memset(Modes.pFileData,127,   MODES_ASYNC_BUF_SIZE);
    memset(Modes.magnitude,  0,   MODES_ASYNC_BUF_SIZE+MODES_PREAMBLE_SIZE+MODES_LONG_MSG_SIZE);

    // Validate the users Lat/Lon home location inputs
    if ( (Modes.fUserLat >   90.0)  // Latitude must be -90 to +90
      || (Modes.fUserLat <  -90.0)  // and 
      || (Modes.fUserLon >  360.0)  // Longitude must be -180 to +360
      || (Modes.fUserLon < -180.0) ) {
        Modes.fUserLat = Modes.fUserLon = 0.0;
    } else if (Modes.fUserLon > 180.0) { // If Longitude is +180 to +360, make it -180 to 0
        Modes.fUserLon -= 360.0;
    }
    // If both Lat and Lon are 0.0 then the users location is either invalid/not-set, or (s)he's in the 
    // Atlantic ocean off the west coast of Africa. This is unlikely to be correct. 
    // Set the user LatLon valid flag only if either Lat or Lon are non zero. Note the Greenwich meridian 
    // is at 0.0 Lon,so we must check for either fLat or fLon being non zero not both. 
    // Testing the flag at runtime will be much quicker than ((fLon != 0.0) || (fLat != 0.0))
    Modes.bUserFlags &= ~MODES_USER_LATLON_VALID;
    if ((Modes.fUserLat != 0.0) || (Modes.fUserLon != 0.0)) {
        Modes.bUserFlags |= MODES_USER_LATLON_VALID;
    }

    // Limit the maximum requested raw output size to less than one Ethernet Block 
    if (Modes.net_output_raw_size > (MODES_RAWOUT_BUF_FLUSH))
      {Modes.net_output_raw_size = MODES_RAWOUT_BUF_FLUSH;}
    if (Modes.net_output_raw_rate > (MODES_RAWOUT_BUF_RATE))
      {Modes.net_output_raw_rate = MODES_RAWOUT_BUF_RATE;}
    if (Modes.net_sndbuf_size > (MODES_NET_SNDBUF_MAX))
      {Modes.net_sndbuf_size = MODES_NET_SNDBUF_MAX;}

    // Initialise the Block Timers to something half sensible
    ftime(&Modes.stSystemTimeBlk);
    for (i = 0; i < MODES_ASYNC_BUF_NUMBER; i++)
      {Modes.stSystemTimeRTL[i] = Modes.stSystemTimeBlk;}

    // Each I and Q value varies from 0 to 255, which represents a range from -1 to +1. To get from the 
    // unsigned (0-255) range you therefore subtract 127 (or 128 or 127.5) from each I and Q, giving you 
    // a range from -127 to +128 (or -128 to +127, or -127.5 to +127.5)..
    //
    // To decode the AM signal, you need the magnitude of the waveform, which is given by sqrt((I^2)+(Q^2))
    // The most this could be is if I&Q are both 128 (or 127 or 127.5), so you could end up with a magnitude 
    // of 181.019 (or 179.605, or 180.312)
    //
    // However, in reality the magnitude of the signal should never exceed the range -1 to +1, because the 
    // values are I = rCos(w) and Q = rSin(w). Therefore the integer computed magnitude should (can?) never 
    // exceed 128 (or 127, or 127.5 or whatever)
    //
    // If we scale up the results so that they range from 0 to 65535 (16 bits) then we need to multiply 
    // by 511.99, (or 516.02 or 514). antirez's original code multiplies by 360, presumably because he's 
    // assuming the maximim calculated amplitude is 181.019, and (181.019 * 360) = 65166.
    //
    // So lets see if we can improve things by subtracting 127.5, Well in integer arithmatic we can't
    // subtract half, so, we'll double everything up and subtract one, and then compensate for the doubling 
    // in the multiplier at the end.
    //
    // If we do this we can never have I or Q equal to 0 - they can only be as small as +/- 1.
    // This gives us a minimum magnitude of root 2 (0.707), so the dynamic range becomes (1.414-255). This 
    // also affects our scaling value, which is now 65535/(255 - 1.414), or 258.433254
    //
    // The sums then become mag = 258.433254 * (sqrt((I*2-255)^2 + (Q*2-255)^2) - 1.414)
    //                   or mag = (258.433254 * sqrt((I*2-255)^2 + (Q*2-255)^2)) - 365.4798
    //
    // We also need to clip mag just incaes any rogue I/Q values somehow do have a magnitude greater than 255.
    //

    for (i = 0; i <= 255; i++) {
        for (q = 0; q <= 255; q++) {
            int mag, mag_i, mag_q;

            mag_i = (i * 2) - 255;
            mag_q = (q * 2) - 255;

            mag = (int) round((sqrt((mag_i*mag_i)+(mag_q*mag_q)) * 258.433254) - 365.4798);

            Modes.maglut[(i*256)+q] = (uint16_t) ((mag < 65535) ? mag : 65535);
        }
    }

    // Prepare error correction tables
    modesInitErrorInfo();
}
Esempio n. 16
0
int main(int argc, char *argv[]) {
  Point start[NUMLINES], end[NUMLINES];
  Color color[NUMLINES];
  Image *src;
  Line line;
  long i,j;
  Color white;
  double tstart, tend;
  long numLines;
  double sum, dx, dy;
  struct timeb tp;

  color_set( &white, 1.0, 1.0, 1.0);

  // allocate an image ROWS by COLS
  src = image_create(ROWS, COLS);
  if(!src) {
    fprintf(stderr, "unable to allocate memory\n");
    exit(0);
  }

  // Initialize the image to all white
  for(i=0;i<src->rows;i++) {
    for(j=0;j<src->cols;j++) {
      image_setColor(src, i, j, white );
    }
  }

  // Pre-calculate the line endpoints and colors so we don't have to
  // call the random() function inside the main drawing loop.
  sum = 0.0;
  for(i=0;i<NUMLINES;i++) {
    int tsx, tsy, tex, tey;
    tsx = (int)(drand48() * COLS);
    tsy = (int)(drand48() * ROWS);
    tex = (int)(drand48() * COLS);
    tey = (int)(drand48() * ROWS);
    point_set2D(&(start[i]), tsx, tsy );
    point_set2D(&(end[i]), tex, tey );
    color[i].c[0] = drand48();
    color[i].c[1] = drand48();
    color[i].c[2] = drand48();

    dx = tsx - tex;
    dy = tsy - tey;
    sum += sqrt(dx * dx + dy * dy);
  }
  sum /= NUMLINES;
  printf("Average line length = %.1lf\n", sum);

  // Start drawing lines
  ftime( &tp );
  tstart = tp.time + tp.millitm / 1000.0;

  for(i=0,numLines=0; numLines < 5000000;numLines++, i++) {
    i = i % NUMLINES;
    line_set(&line, start[i], end[i]);
    line_draw(&line, src, color[i]);
  }

  ftime( &tp );
  tend = tp.time + tp.millitm / 1000.0;

  // print out the result
  printf("%.2lf lines per second\n", numLines / (tend - tstart) );

  // write out the image
  image_write(src, "lines.ppm");

  // free the image data
  image_free(src);

  return(0);
}
Esempio n. 17
0
void tu_timer::init_timer()
{
	ftime(&s_start_time);
}
Esempio n. 18
0
JSInt64
PRMJ_Now(void)
{
#ifdef XP_OS2
    JSInt64 s, us, ms2us, s2us;
    struct timeb b;
#endif
#ifdef XP_WIN
    JSInt64 s, us,
    win2un = JSLL_INIT(0x19DB1DE, 0xD53E8000),
    ten = JSLL_INIT(0, 10);
    FILETIME time, midnight;
#endif
#if defined(XP_UNIX) || defined(XP_BEOS)
    struct timeval tv;
    JSInt64 s, us, s2us;
#endif /* XP_UNIX */
#ifdef XP_MAC
    JSUint64 upTime;
    JSInt64	 localTime;
    JSInt64       gmtOffset;
    JSInt64    dstOffset;
    JSInt32       gmtDiff;
    JSInt64	 s2us;
#endif /* XP_MAC */

#ifdef XP_OS2
    ftime(&b);
    JSLL_UI2L(ms2us, PRMJ_USEC_PER_MSEC);
    JSLL_UI2L(s2us, PRMJ_USEC_PER_SEC);
    JSLL_UI2L(s, b.time);
    JSLL_UI2L(us, b.millitm);
    JSLL_MUL(us, us, ms2us);
    JSLL_MUL(s, s, s2us);
    JSLL_ADD(s, s, us);
    return s;
#endif
#ifdef XP_WIN
    /* The windows epoch is around 1600. The unix epoch is around 1970.
       win2un is the difference (in windows time units which are 10 times
       more precise than the JS time unit) */
    GetSystemTimeAsFileTime(&time);
    /* Win9x gets confused at midnight
       http://support.microsoft.com/default.aspx?scid=KB;en-us;q224423
       So if the low part (precision <8mins) is 0 then we get the time
       again. */
    if (!time.dwLowDateTime) {
        GetSystemTimeAsFileTime(&midnight);
        time.dwHighDateTime = midnight.dwHighDateTime;
    }
    JSLL_UI2L(s, time.dwHighDateTime);
    JSLL_UI2L(us, time.dwLowDateTime);
    JSLL_SHL(s, s, 32);
    JSLL_ADD(s, s, us);
    JSLL_SUB(s, s, win2un);
    JSLL_DIV(s, s, ten);
    return s;
#endif

#if defined(XP_UNIX) || defined(XP_BEOS)
#ifdef _SVID_GETTOD   /* Defined only on Solaris, see Solaris <sys/types.h> */
    gettimeofday(&tv);
#else
    gettimeofday(&tv, 0);
#endif /* _SVID_GETTOD */
    JSLL_UI2L(s2us, PRMJ_USEC_PER_SEC);
    JSLL_UI2L(s, tv.tv_sec);
    JSLL_UI2L(us, tv.tv_usec);
    JSLL_MUL(s, s, s2us);
    JSLL_ADD(s, s, us);
    return s;
#endif /* XP_UNIX */
#ifdef XP_MAC
    JSLL_UI2L(localTime,0);
    gmtDiff = PRMJ_LocalGMTDifference();
    JSLL_I2L(gmtOffset,gmtDiff);
    JSLL_UI2L(s2us, PRMJ_USEC_PER_SEC);
    JSLL_MUL(gmtOffset,gmtOffset,s2us);

    /* don't adjust for DST since it sets ctime and gmtime off on the MAC */
    Microseconds((UnsignedWide*)&upTime);
    JSLL_ADD(localTime,localTime,gmtOffset);
    JSLL_ADD(localTime,localTime, dstLocalBaseMicroseconds);
    JSLL_ADD(localTime,localTime, upTime);

    dstOffset = PRMJ_DSTOffset(localTime);
    JSLL_SUB(localTime,localTime,dstOffset);

    return *((JSUint64 *)&localTime);
#endif /* XP_MAC */
}
Esempio n. 19
0
int getMilliCount(){
	timeb tb;
	ftime(&tb);
	int nCount = tb.millitm + (tb.time & 0xfffff) * 1000;
	return nCount;
}
Esempio n. 20
0
int HPCupsFilter::StartPrintJob(int  argc, char *argv[])
{
    int              fd = 0;
    cups_raster_t    *cups_raster;
    int              err = 0;

    memset(&m_JA, 0, sizeof(JobAttributes));
    struct    tm       *t;
    struct    timeb    tb;
    time_t             long_time;
    time(&long_time);
    t = localtime(&long_time);
    ftime(&tb);
    strncpy(m_JA.job_start_time, asctime(t), sizeof(m_JA.job_start_time)-1);    // returns Fri Jun  5 08:12:16 2009
    snprintf(m_JA.job_start_time+19, sizeof(m_JA.job_start_time) - 20, ":%d %d", tb.millitm, t->tm_year + 1900); // add milliseconds

    getLogLevel();
    m_JA.job_id = atoi(argv[1]);
    FILE    *fp;
    char    dFileName[32];
    memset(dFileName, 0, sizeof(dFileName));
    m_JA.job_id = atoi(argv[1]);
    snprintf (dFileName, sizeof(dFileName), "/var/spool/cups/d%05d-001", m_JA.job_id);
    if ((fp = fopen (dFileName, "r")))
    {
        char    line[258];
        for (int i = 0; i < 10; i++)
        {
            fgets (line, 256, fp);
            if (!strncmp (line, "%%Pages:", 8))
            {
                sscanf (line+9, "%d", &m_JA.total_pages);
                break;
            }
        }
        fclose (fp);
    }

    m_ppd = ppdOpenFile(getenv("PPD"));
    if (m_ppd == NULL) {
        dbglog("DEBUG: ppdOpenFile failed for %s\n", getenv("PPD"));
        return SYSTEM_ERROR;
    }

    m_argv = argv;
    if (m_iLogLevel & BASIC_LOG) {
        for (int i = 0; i < argc; i++) {
            dbglog("argv[%d] = %s\n", i, argv[i]);
        }
    }

    if (argc == 7)
    {
        if (m_iLogLevel & BASIC_LOG)
        {
            dbglog("Page Stream Data Name: %s\n", argv[6] );
        }
        if ((fd = open (argv[6], O_RDONLY)) == -1)
        {
            perror("ERROR: Unable to open raster file - ");
            return 1;
        }
    }

    m_pSys = new SystemServices(m_iLogLevel, m_JA.job_id);

/*
 *  When user cancels a print job, the spooler sends SIGTERM signal
 *  to the filter. Must catch this signal to send end job sequence
 *  to the printer.
 */

    signal(SIGTERM, HPCancelJob);

    cups_raster = cupsRasterOpen(fd, CUPS_RASTER_READ);

    if (cups_raster == NULL) {
        dbglog("cupsRasterOpen failed, fd = %d\n", fd);
        if (fd != 0) {
            close(fd);
        }
        closeFilter();
        return 1;
    }

    if ((err = processRasterData(cups_raster))) {
        if (fd != 0) {
            close(fd);
        }
        if (m_iLogLevel & BASIC_LOG)
            dbglog("HPCUPS: processRasterData returned %d, calling closeFilter()", err);
        closeFilter();
        cupsRasterClose(cups_raster);
        return 1;
    }

    if (fd != 0) {
        close(fd);
    }
    if (m_iLogLevel & BASIC_LOG)
        dbglog("HPCUPS: StartPrintJob end of job, calling closeFilter()");
    closeFilter();
    cupsRasterClose(cups_raster);
    return 0;
}
Esempio n. 21
0
//using namespace std;
int main(int argc, char *argv[])
{
	FBFR32 *sendbuf, *rcvbuf;
	
	long ret, numread = 0;
	char sOrderListID[13]={0}; 
	char sAreaCode[10]={0};
	char sInXML[MAX_XML_SIZE];
	char sOutXML[MAX_XML_SIZE];
	
	char sFileName[30];	
	long lResult;
	char sErrMsg[1000];
	struct  timeb  tp1,tp2;
	memset(sOutXML, 0, MAX_XML_SIZE);
	memset(sErrMsg, 0, 1000);
	memset(sFileName, 0, 30);
	strcpy(sFileName, (char*)argv[1]);
	
	printf("you input  fileName is <%s>\n",  sFileName);

	FILE *fp;
	if((fp = fopen(sFileName, "r")) == NULL)
	{
		printf("can't open file: %s\n", sFileName);
		return 0;
	}
	numread = fread(sInXML, sizeof(char), MAX_XML_SIZE, fp);
	printf("read size is %d\n", numread);
	fclose(fp);

	long rcvlen = 0L;
	
	if ((sendbuf = (FBFR32*)tpalloc("FML32", NULL,MAX_XML_SIZE ))==NULL)
	{
		printf("分配发送buff error\n");
	}
	
	if ((rcvbuf = (FBFR32*)tpalloc("FML32", NULL, MAX_XML_SIZE))==NULL)
	{
		printf("分配接收buff error\n");
	}
	
	rcvlen = Fsizeof32(rcvbuf);
	//初始化	
	//if ((ret=tpinit((TPINIT * )NULL))<0)
	if ((ret=tpinit(NULL))<0)
	{
		printf( "tpinit fail\n");
		tpfree((char *)sendbuf);
		tpfree((char *)rcvbuf);
		return -1;
	}
	
	Fchg32(sendbuf, IN_XML, 0, (char *)&sInXML, 0L);
	ftime(&tp1);
		
	ret=tpcall("POWER_CTL_RUN",(char*)sendbuf,0L,(char**)&rcvbuf,&rcvlen,0L);
	ftime(&tp2);
	
	if (Fgets32(rcvbuf, OUT_XML, 0, sOutXML) == -1)
	{
		printf( " OUT_XML error \n");
	}
	if (Fget32(rcvbuf, IRESULT, 0, (char*)&lResult, 0) == -1)
	{
		printf( " IRESULT error \n");
	}
	if (Fgets32(rcvbuf, SMSG, 0, sErrMsg) == -1)
	{
		printf( " SMSG error \n");
	}
	
	printf("InXML is %s\n", sInXML);
	printf("OutXML is : %s\n", sOutXML);
	printf("Result is : %ld\n", lResult);
	printf("ErrMsg is : %s\n", sErrMsg); 
	printf("  用时: %d ms\n",  tp2.time*1000+tp2.millitm - tp1.time*1000 -tp1.millitm );

	return 0;
}
Esempio n. 22
0
int main(int argc, char **argv) {
	if(SDL_Init(SDL_INIT_VIDEO) < 0) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
		return -1;
	}

	if(TTF_Init() < 0) {
		fprintf(stderr, "Couldn't initialize font rendering: %s\n", TTF_GetError());
		return -1;
	}

  int width = 800;
  int height = 600;
  Uint32 frameRate = BASE_FRAME_RATE_MS;
  SDL_bool vsync = SDL_FALSE;

#if SDL_MAJOR_VERSION == 2
  SDL_DisplayMode current;
  for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i){
    if(SDL_GetCurrentDisplayMode(i, &current) != 0)
			fprintf(stderr, "Couldn't get display mode: %s\n", SDL_GetError());
    else {
      printf("Display %d is %dx%d\n", i, current.w, current.h);
      width = current.w;
      height = current.h;
    }
  }

	Uint32 flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC;
	if(argc > 1) {
		if(strncmp(argv[1], "-novsync", 8) == 0)
			flags &= ~SDL_RENDERER_PRESENTVSYNC;
		if(strncmp(argv[1], "-software", 9) == 0)
			flags = SDL_RENDERER_SOFTWARE;

		char *n = strchr(argv[1], '=');
		if(n) {
			n++;
			frameRate = strtoul(n, 0, 0);
		}
	}

	SDL_Window *window = SDL_CreateWindow(argv[0], SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width + GetIntelOffset(), height, SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN);
	SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, flags);
	SDL_ShowCursor(SDL_DISABLE);
	SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
	SDL_DisableScreenSaver();

	SDL_RendererInfo info;
	if(SDL_GetRendererInfo(renderer, &info) == 0) {
		printf("Using video driver: %s with renderer %s\n", SDL_GetCurrentVideoDriver(), info.name);
		if(info.flags & SDL_RENDERER_SOFTWARE)
			printf("*** Using SDL_RENDERER_SOFTWARE\n");
		if(info.flags & SDL_RENDERER_ACCELERATED)
			printf("*** Using SDL_RENDERER_ACCELERATED\n");
		if(info.flags & SDL_RENDERER_PRESENTVSYNC) {
			printf("*** Using SDL_RENDERER_PRESENTVSYNC\n");
			vsync = SDL_TRUE;
		}
		if(info.flags & SDL_RENDERER_TARGETTEXTURE)
			printf("*** Using SDL_RENDERER_TARGETTEXTURE\n");
	}
#else
  const SDL_VideoInfo *pVideoInfo = SDL_GetVideoInfo();
  if(pVideoInfo == 0) {
    fprintf(stderr, "Couldn't get display information: %s\n", SDL_GetError());
    exit(1);
  }
  printf("Display is %dx%d\n", pVideoInfo->current_w, pVideoInfo->current_h);
  width = pVideoInfo->current_w;
  height = pVideoInfo->current_h;

  SDL_Surface *screen = SDL_SetVideoMode(width, height, pVideoInfo->vfmt->BitsPerPixel, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN);
  if(screen == 0) {
    fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError());
    exit(1);
  }

  SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  SDL_ShowCursor(SDL_DISABLE);

#endif

	TTF_Font *font = TTF_OpenFont("AlteHaasGroteskBold.ttf", 60);
	if(font == 0) {
		fprintf(stderr, "Can't open font for stats: %s", TTF_GetError());
		goto cleanup;
	}

	SDL_Event event;
	SDL_bool m_run = SDL_TRUE;
	Uint32 lastFrame = 0;
	float fps = 0.0f;
	SDL_Color foregroundColor = { 0xff, 0xff, 0 };
	char tmp[64];
	int delta = 1;
	int position = 0;
	while(m_run) {
		while(SDL_PollEvent(&event)) {
			switch (event.type) {
			case SDL_KEYDOWN:
				if(event.key.keysym.sym == SDLK_ESCAPE)
				m_run = SDL_FALSE;
				break;
			case SDL_QUIT:
				m_run = SDL_FALSE;
				break;
			default:
				break;
			}
		}

		Uint32 start = SDL_GetTicks();

#if SDL_MAJOR_VERSION == 2
		SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0xff);
		SDL_RenderClear(renderer);
#else
    SDL_FillRect(screen, 0, 0);
#endif

		snprintf(tmp, sizeof(tmp), "Current fps = %.1f", fps);
		SDL_Surface *textSurface = TTF_RenderText_Solid(font, tmp, foregroundColor);

		if(textSurface) {
#if SDL_MAJOR_VERSION == 2
			SDL_Texture *textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
#endif

			SDL_Rect location;
			location.h = textSurface->h;
			location.w = textSurface->w;
			location.x = position;
			location.y = height / 2 - textSurface->h / 2;
#if SDL_MAJOR_VERSION == 1
      SDL_BlitSurface(textSurface, 0, screen, &location);
#endif
			SDL_FreeSurface(textSurface);

			position += delta;
			if(position >= width - textSurface->w || position <= 0)
				delta *= -1;

#if SDL_MAJOR_VERSION == 2
			if(textTexture) {
				SDL_RenderCopy(renderer, textTexture, 0, &location);
				SDL_DestroyTexture(textTexture);
			}
#endif
		}

#if SDL_MAJOR_VERSION == 2
		SDL_RenderPresent(renderer);
#else
    SDL_Flip(screen);
#endif

		Uint32 end = SDL_GetTicks();
		Uint32 elapsed = end - lastFrame;

		// delay for the remainder of the base rate so we keep a decent frame rate if there's no vsync
		if(vsync == SDL_FALSE && frameRate > elapsed)
			SDL_Delay(frameRate - elapsed);

		if(elapsed > frameRate * 3) {
			struct timeb tp;
			ftime(&tp);
			time_t now;
			struct tm *ti;
			char buf[255];
			time(&now);
			ti = localtime(&now);
			strftime(buf, sizeof(buf), "%I:%M:%S", ti);
			printf("%s.%d: Frame took %ums\n", buf, tp.millitm, elapsed);
		}

		// remember now as the starting point for the next frame
		lastFrame = SDL_GetTicks();

		// update statistics
		elapsed = lastFrame - start;
		fps = 1000.0f / (float)elapsed;
		//printf("Current frame rate is %6.3f fps (%ums)              \r", fps, elapsed);
	}
	printf("\n");

cleanup:
#if SDL_MAJOR_VERSION == 2
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
#else
  SDL_FreeSurface(screen);
#endif
	TTF_Quit();
	SDL_Quit();

	return 0;
}
void MutexKnobData::initHighestCountPV()
{
    QMutexLocker locker(&mutex);
    ftime(&monitorTiming);
    highestCount = 0;
}
Esempio n. 24
0
float sendRequestedDataCallback(
                                   float	inElapsedSinceLastCall,
                                   float	inElapsedTimeSinceLastFlightLoop,
                                   int		inCounter,
                                   void *	inRefcon) {

	int i;
	int res;
#if IBM
	char msg[80];
#endif
	struct RequestRecord rr;

	if( DEBUG ) {
		XPLMDebugString("XData: sendRequestedDataCallback called.\n");
	}

	if (xdata_plugin_enabled && xdata_send_enabled && xdata_socket_open) {
	
		if( acf_packet_requested == 1 ) {			
			acf_packet_requested = 0;
			sendAircraftPacket();
		}
	
		// Tried a number of things, but absolute current time in millis just overflows and isn't printable via sprintf, it seems, as a long long.
		// So: initializing a start time, then evaluating time since that, which fits into an int.
		if( t_start.time == 0 ) {
			ftime(&t_start);
			XPLMDebugString("Initialising t_start.\n");
		}


		struct timeb t_current;
		ftime(&t_current);
		int t_diff = (int) (1000.0 * (t_current.time - t_start.time) + (t_current.millitm - t_start.millitm));
		
		// clear the buffer
		memset(response_data, 0, response_max_size);
		
//		sprintf(msg, "Time check: milliseconds since start = %d\n", t_diff);
//		XPLMDebugString(msg);
				
		strncpy(response_data, "REQD", 4);		// first 4 bytes indicate packet type
		response_index = 8;
		number_of_points = 0;
		
		// work out which requests to send
		for( i=0; i<=max_requested_index; i++ ) {
			rr = request_records[i];
			if( rr.enabled && request_records[i].dataref != NULL ) {
				//sprintf(msg, "%d - Checking %s which is scheduled for %d\n", t_diff, rr.dataref_name, rr.time_next_send);
				//XPLMDebugString(msg);
				if( rr.time_next_send == 0 || t_diff > rr.time_next_send ) {
					
					// let's work out the size of the data
					int size = 0;
					
					int nbrArrayValues = 0;
					
					int intValue = 0;
					float floatValue = 0.0f;
					double doubleValue = 0.0;
					int intArrayValues[20];
					float floatArrayValues[20];
					char data[900];
					
					if( request_records[i].datatype == xplmType_Int ) {
						intValue = XPLMGetDatai(request_records[i].dataref);
						size = 4;
					} else
					if( request_records[i].datatype == xplmType_Float ) {
						floatValue = XPLMGetDataf(request_records[i].dataref);
						size = 4;
					} else
					if( request_records[i].datatype == xplmType_Double || request_records[i].datatype == 6 ) {  // hack based on observed values
						doubleValue = XPLMGetDatad(request_records[i].dataref);
						size = 8;
					} else			
					if( request_records[i].datatype == xplmType_FloatArray ) {
						nbrArrayValues = XPLMGetDatavf(request_records[i].dataref, floatArrayValues, 0, 20);
						size = (4 * nbrArrayValues);
					} else
					if( request_records[i].datatype == xplmType_IntArray ) {
						nbrArrayValues = XPLMGetDatavi(request_records[i].dataref, intArrayValues, 0, 20);
						size = (4 * nbrArrayValues);
					} else
					if( request_records[i].datatype == xplmType_Data ) {
						nbrArrayValues = XPLMGetDatab(request_records[i].dataref, data, 0, 900);
						size = nbrArrayValues;
					}
				
					
					// will it fit in the buffer
					int index_after_add = response_index + 4 + 4 + 4 + size;
					if( index_after_add >= response_max_size ) {
						// if not, send it
						// first update response with number of points
						int convertedNum = custom_htonl(number_of_points);
						memcpy(response_data+4, &convertedNum, 4);
						
						if( DEBUG ) {
							sprintf(msg, "Packet ready to go: number_of_points=%d response_index=%d\n", number_of_points, response_index);
							XPLMDebugString(msg);
							XPLMDebugString("Packet data: ");
							int p=0;
							for( p=0; p<response_index; p++ ) {
								sprintf(msg, "%d:%d ", p, (int)response_data[p]);
								XPLMDebugString(msg);
							}
							XPLMDebugString("\n");
						}
						
						// ready to go	
						for (i=0; i<NUM_DEST; i++) {
							if (dest_enable[i]) {
								res = sendto(sockfd, response_data, response_index, 0, (struct sockaddr *)&dest_sockaddr[i], sizeof(struct sockaddr));
				#if IBM
								if ( res == SOCKET_ERROR ) {
									XPLMDebugString("XData: caught error while sending REQD packet! (");
									sprintf(msg, "%d", WSAGetLastError());
									XPLMDebugString(msg);
									XPLMDebugString(")\n");
								}
				#else
								if ( res < 0 ) {
									XPLMDebugString("XData: caught error while sending REQD packet! (");
									XPLMDebugString((char * const) strerror(GET_ERRNO));
									XPLMDebugString(")\n");
								}
				#endif
							}
						}
						
						XPLMDebugString("Sent packet\n");						
						response_index = 8;
						number_of_points = 0;
						
					} else {			
						// otherwise add it to the buffer
						
						// TODO figure out how to either convert each of the above datatypes into char[] data, or
						// simply memcpy from the original dataref into the buffer.
						
						// ID|DATATYPE|LENGTH|DATA....
						int convertedI = custom_htonl(i);
						memcpy(response_data+response_index, &convertedI, 4);
						response_index += 4;
						
						int convertedDatatype = custom_htonl(request_records[i].datatype);
						memcpy(response_data+response_index, &convertedDatatype, 4);
						response_index += 4;
						
						int convertedSize = custom_htonl(size);
						memcpy(response_data+response_index, &convertedSize, 4);
						response_index += 4;

						if( request_records[i].datatype == xplmType_Int ) {
							int convertedInt = custom_htonl(intValue);
							memcpy(response_data+response_index, &convertedInt, 4);
							response_index += 4;
						} else
						if( request_records[i].datatype == xplmType_Float ) {
							// skipping endianness conversion of float too, similar problem to double?
							//float convertedFloat = custom_htonf(floatValue);
							memcpy(response_data+response_index, &floatValue, 4);
							response_index += 4;
							if( DEBUG ) {
								sprintf(msg, "Converted a float: %f\n", floatValue);
								XPLMDebugString(msg);
								sprintf(msg, "%d %d %d %d\n", (int)response_data[response_index-4], (int)response_data[response_index-3], (int)response_data[response_index-2], (int)response_data[response_index-1]);
								XPLMDebugString(msg);								
							}							
						} else
						if( request_records[i].datatype == xplmType_Double || request_records[i].datatype == 6 ) {  // hack based on observed values
						
							// Now this is weird.  Converting the double breaks it somehow.  Even reversing the byte order at the receiving
							// end doesn't work..
							//double convertedDouble = custom_htond(doubleValue);
							memcpy(response_data+response_index, &doubleValue, 8);
							response_index += 8;
						} else			
						if( request_records[i].datatype == xplmType_FloatArray ) {
							int d = 0;
							for( d = 0; d<nbrArrayValues; d++ ) {
								float convertedFloat = custom_htonf(floatArrayValues[d]);
								memcpy(response_data+response_index, &convertedFloat, 4);
								response_index += 4;
							}
						} else
						if( request_records[i].datatype == xplmType_IntArray ) {
							int d = 0;
							for( d = 0; d<nbrArrayValues; d++ ) {
								int convertedInt = custom_htonl(intArrayValues[d]);
								memcpy(response_data+response_index, &convertedInt, 4);
								response_index += 4;
							}
						} else
						if( request_records[i].datatype == xplmType_Data ) {
							memcpy(response_data+response_index, &data, size);
							response_index += size;
						}
						
						
						
						
						
						response_index = index_after_add;
						number_of_points++;	
						
						if( DEBUG ) {
							sprintf(msg, "Packet accumulating: number_of_points=%d response_index=%d\n", number_of_points, response_index);
							XPLMDebugString(msg);						
						}
						
					}

					// schedule next time
					request_records[i].time_next_send = t_diff + rr.every_millis;
//					sprintf(msg, "%d - Would send %s and rescheduled (every %d millis) for %d\n", t_diff, rr.dataref_name, rr.every_millis, rr.time_next_send);
//					XPLMDebugString(msg);
				}
			}
		}
		
		// does the buffer contain any data?
		if( number_of_points > 0 ) {
			// send it
			
			// first update response with number of points
			int convertedNum = custom_htonl(number_of_points);
			memcpy(response_data+4, &convertedNum, 4);
			
			if( DEBUG ) {
				sprintf(msg, "Packet ready to go: number_of_points=%d response_index=%d\n", number_of_points, response_index);
				XPLMDebugString(msg);
				XPLMDebugString("Packet data: ");
				int p=0;
				for( p=0; p<response_index; p++ ) {
					sprintf(msg, "%d:%d ", p, (int)response_data[p]);
					XPLMDebugString(msg);
				}
				XPLMDebugString("\n");
			}
			
			// ready to go		
			for (i=0; i<NUM_DEST; i++) {
				if (dest_enable[i]) {
					res = sendto(sockfd, response_data, response_index, 0, (struct sockaddr *)&dest_sockaddr[i], sizeof(struct sockaddr));
	#if IBM
					if ( res == SOCKET_ERROR ) {
						XPLMDebugString("XData: caught error while sending REQD packet! (");
						sprintf(msg, "%d", WSAGetLastError());
						XPLMDebugString(msg);
						XPLMDebugString(")\n");
					}
	#else
					if ( res < 0 ) {
						XPLMDebugString("XData: caught error while sending REQD packet! (");
						XPLMDebugString((char * const) strerror(GET_ERRNO));
						XPLMDebugString(")\n");
					}
	#endif
				}
			}
			
			if( DEBUG ) {
				XPLMDebugString("Sent packet.\n");				
			}
		}
		
/*
	long		time_last_sent;
	long 		every_millis;
	long		time_next_send;
	
	
every 100 ms, create a buffer (well, reuse it for performance) and start populating it with eligible data.  Keep going until the next ref would overflow the buffer.
 send the packet, then resume from the current ref.  until there are no more eligible refs.  send that last packet, if there's something in it.
 upon adding the data to the packet, update the struct with the calculated next send time.
 
REQD|COUNT|ID|DATATYPE|LENGTH|DATA.....................................|(repeated ID, TYPE, LEN, DATA)..

	
*/	
	
/*
		packet_size = createSituationPacket();

		for (i=0; i<NUM_DEST; i++) {
			if (dest_enable[i]) {
				res = sendto(sockfd, (const char*)&sim_packet, packet_size, 0, (struct sockaddr *)&dest_sockaddr[i], sizeof(struct sockaddr));
#if IBM
				if ( res == SOCKET_ERROR ) {
					XPLMDebugString("XData: caught error while sending REQD packet! (");
                    sprintf(msg, "%d", WSAGetLastError());
					XPLMDebugString(msg);
					XPLMDebugString(")\n");
				}
#else
				if ( res < 0 ) {
					XPLMDebugString("XData: caught error while sending REQD packet! (");
					XPLMDebugString((char * const) strerror(GET_ERRNO));
					XPLMDebugString(")\n");
				}
#endif
			}
		}
*/
		return 0.1;

	} else {

		// print something to allow us to work out what happened.
		XPLMDebugString("XData: plugin enabled:");
		if( xdata_plugin_enabled ) {
			XPLMDebugString("true\n");
		} else {
			XPLMDebugString("false\n");
		}

		XPLMDebugString("XData: send enabled:");
		if( xdata_send_enabled ) {
			XPLMDebugString("true\n");
		} else {
			XPLMDebugString("false\n");
		}

		XPLMDebugString("XData: socket open:");
		if( xdata_socket_open ) {
			XPLMDebugString("true\n");
		} else {
			XPLMDebugString("false\n");
		}
	
		return 0.1f;
	}

}
Esempio n. 25
0
static void perf_get_info(FB_API_HANDLE* handle, P* perf)
{
/**************************************
 *
 *	P E R F _ g e t _ i n f o
 *
 **************************************
 *
 * Functional description
 *	Acquire timing and performance information.  Some info comes
 *	from the system and some from the database.
 *
 **************************************/
	SSHORT buffer_length, item_length;
	ISC_STATUS_ARRAY jrd_status;
#ifdef HAVE_GETTIMEOFDAY
	struct timeval tp;
#else
	struct timeb time_buffer;
#define LARGE_NUMBER 696600000	// to avoid overflow, get rid of decades)
#endif

	// If there isn't a database, zero everything out

	if (!*handle) {
		memset(perf, 0, sizeof(PERF));
	}

	// Get system time

	times(&perf->perf_times);

#ifdef HAVE_GETTIMEOFDAY
	GETTIMEOFDAY(&tp);
	perf->perf_elapsed = tp.tv_sec * 100 + tp.tv_usec / 10000;
#else
	ftime(&time_buffer);
	perf->perf_elapsed = (time_buffer.time - LARGE_NUMBER) * 100 + (time_buffer.millitm / 10);
#endif

	if (!*handle)
		return;

	SCHAR buffer[256];
	buffer_length = sizeof(buffer);
	item_length = sizeof(items);
	isc_database_info(jrd_status, handle, item_length, items, buffer_length, buffer);

	const char* p = buffer;

	while (true)
		switch (*p++)
		{
		case isc_info_reads:
			perf->perf_reads = get_parameter(&p);
			break;

		case isc_info_writes:
			perf->perf_writes = get_parameter(&p);
			break;

		case isc_info_marks:
			perf->perf_marks = get_parameter(&p);
			break;

		case isc_info_fetches:
			perf->perf_fetches = get_parameter(&p);
			break;

		case isc_info_num_buffers:
			perf->perf_buffers = get_parameter(&p);
			break;

		case isc_info_page_size:
			perf->perf_page_size = get_parameter(&p);
			break;

		case isc_info_current_memory:
			perf->perf_current_memory = get_parameter(&p);
			break;

		case isc_info_max_memory:
			perf->perf_max_memory = get_parameter(&p);
			break;

		case isc_info_end:
			return;

		case isc_info_error:
			switch (p[2])
			{
			 case isc_info_marks:
				perf->perf_marks = 0;
				break;
			case isc_info_current_memory:
				perf->perf_current_memory = 0;
				break;
			case isc_info_max_memory:
				perf->perf_max_memory = 0;
				break;
			}

			{
				const SLONG temp = isc_vax_integer(p, 2);
				fb_assert(temp <= MAX_SSHORT);
				p += temp + 2;
			}

			perf->perf_marks = 0;
			break;

		default:
			return;
		}
}
Esempio n. 26
0
int can_dev_interrupt(IOFUNC_ATTR_T *pattr)
{
	int i=0;
	int s;
	int retval = 0;	// set to 1 for receive
#ifdef DO_TRACE
	struct timeb current;
	ftime(&current);
	printf("interrupt: sec %d ms %3d\n", current.time, current.millitm);
	fflush(stdout);
#endif
	while((INTERRUPT_VALUE=Read_REG(INT_REG)))
	{

	if(i>0) {
		intr_in_handler_count++; 
#ifdef DO_TRACE
		printf("i %d:%s intval=%d\n",i,pattr->devname,INTERRUPT_VALUE);
#endif
	}
	++i;
			
	STATUS=Read_REG(STATUS_REG);
#ifdef DO_TRACE
	printf("interrupt: value 0x%02x, status 0x%02x\n", 
			INTERRUPT_VALUE, STATUS);
	fflush(stdout);
#endif	
	switch(INTERRUPT_VALUE)
	{
	case 0x01:
		if((STATUS & 0x80)!=0)
		{
			printf("Bus off: error counter=256\n");
			fflush(stdout);
			//no sei se ir funcionar
			can_dev_init(BaseAddress,Speed,set_extended_frame);
			return 0; //ou exit() se o passo anterior no funcionar
		}
		if((STATUS & 0x40)!=0)
		{
			if(BaseAddress == 1074790400)
				fprintf(stderr,"Warning: error counter>95, broken can1 cable\n");
			if(BaseAddress == 1074790656)
				fprintf(stderr,"Warning: error counter>95, broken can2 cable\n");
			fflush(stdout);
			STATUS = STATUS & ~0x40;	//Limpa Warning
			Write_REG(STATUS_REG,STATUS);
		}
		
		break;
	case 0x02:
   		s=0;
   		while (Read_REG(MSG_15+CTRL_1_REG) & 0x02)
   		{
   			if(s>0) {
				shadow_buffer_count++;
#ifdef DO_TRACE
   				printf("shadow buffer: %d\n",s);
				fflush(stdout);
#endif
			}
   			++s;
   			retval = 1;	
			rx_interrupt_count++;
#ifdef DO_TRACE
			printf("RX interrupt\n");
			fflush(stdout);
#endif
   			Interrupt_Request_Rx(pattr);
			Write_REG(MSG_15+CTRL_0_REG,0xFD);  /* Reset IntPnd */ 
			Write_REG(MSG_15+CTRL_1_REG,0xFD);  /* 11111101 Reset NewDat*/
		}
		
		//este teste consome algum tempo que pode ser precioso. 
		//Pode indicar mensagens perdidas que realmente no foram perdidas
		if (Read_REG(MSG_15+CTRL_1_REG) & 0x08) /* MsgLst */
		{
			Write_REG(MSG_15+CTRL_1_REG,0xF7); /* Reset MsgLst */
			rx_message_lost_count++;
#ifdef DO_TRACE_RX
			printf("message lost\n");
			fflush(stdout);
#endif
		}

		break;
	case 0x03:
   		Write_REG(MSG_1+CTRL_0_REG,0xFD);  /* Reset IntPnd */ 
#ifdef DO_TRACE_TX
		printf("TX interrupt\n");
		fflush(stdout);
#endif
		tx_interrupt_count++;
		Interrupt_Request_Tx(pattr);
		break;		
	default:
		printf("Unexpected interrupt: %d\n",INTERRUPT_VALUE);
		fflush(stdout);
		// Should add code to clear interrupt
		if (i > 20) return (retval);
		break;
	}

	}
    return (retval);
}
Esempio n. 27
0
void byte_at_a_time(void)

{
	//Variable declarations 
	char input_file_name[64], new_file_name[64];
	FILE * input_file;
	FILE * copy_file;
	//Buffer
	char buff;	
	//Timing
	struct timeb clock_start, clock_end;
	clock_t cpu_start, cpu_end;
	int wall_diff = 0, cpu_diff = 0;

#ifdef WIN32
	char EOL[] = "\r\n";
#else
	char EOL[] = "\n";
#endif

	//Open file to be read. 
	printf("Enter name of file to open, be sure to include .txt when typing name: ");
	scanf("%63s", input_file_name);
	input_file = fopen(input_file_name,"r");
	while (input_file == NULL)
	{
		printf("File not found please make sure file is in the correct direcory andand the name is correct, \n then try again, use exit to leave: ");	
		scanf("%63s", input_file_name);
		input_file = fopen(input_file_name, "r");
		if(input_file_name == "exit")
		{
			exit(0);
		}
	}


	//Open file to copy to.
	printf("Enter name of file to write to: ");
	scanf("%63s", new_file_name);
	copy_file = fopen(new_file_name,"w");
	while (copy_file == NULL)
	{
		printf("File not found please make sure file is in the correct direcory andand name is correct, \n then try again: ");
		scanf("%63s", new_file_name);
		copy_file = fopen(new_file_name, "w");
		if(new_file_name == "exit")
		{
			exit(0);
		}
	}	

	//Copy file into new file
	
	if(input_file != NULL && copy_file != NULL)
	{
		printf("Starting copy:\n");
		ftime(&clock_start);
		cpu_start = clock();
		while(fscanf(input_file, "%c", &buff) != EOF)
		{
			if(buff != '\n')
			{
				fprintf(copy_file, "%c", buff);
			}
			if(buff == '\n')
			{
				fprintf(copy_file, "%s", EOL);
			}
		}
	}
	fclose(input_file);
	fclose(copy_file);
	ftime(&clock_end);
	cpu_end = clock();

	//Find wall time andand cpu time
	wall_diff = (1000 * (clock_end.time - clock_start.time) + (clock_end.millitm - clock_start.millitm));
	cpu_diff = (cpu_end - cpu_start) / (CLOCKS_PER_SEC / (clock_t)1000);

	printf("Task completed in %d milliseconds Wall-clock time and %d milliseconds CPU time.\n", wall_diff, cpu_diff);
}
Esempio n. 28
0
static long
RunLoadTest(struct clientParms *parms, struct rx_connection *conn)
{
    long code;
    struct client c;
    u_long fastCalls[MAX_CTHREADS];
    u_long slowCalls[MAX_CTHREADS];
    u_long copiousCalls[MAX_CTHREADS];
    double start, interval;

    DivideUpCalls(parms->fastCalls, parms->threads, fastCalls);
    DivideUpCalls(parms->slowCalls, parms->threads, slowCalls);
    DivideUpCalls(parms->copiousCalls, parms->threads, copiousCalls);

    memset(&c, 0, sizeof(c));
    c.conn = conn;
    c.sendLen = parms->sendLen;
    c.recvLen = parms->recvLen;
    c.fastCalls = fastCalls;
    c.slowCalls = slowCalls;
    c.copiousCalls = copiousCalls;

    start = ftime();
    code = CallSimultaneously(parms->threads, &c, DoClient);
    if (code) {
	afs_com_err(whoami, code, "in DoClient");
	return code;
    }
    interval = ftime() - start;

    if (parms->printTiming) {
	u_long totalCalls =
	    parms->fastCalls + parms->slowCalls + parms->copiousCalls;
	int t = (interval / totalCalls) * 1000.0 + 0.5;
	if (totalCalls > 0) {
	    printf("For %lu calls: %d msec/call\n", totalCalls, t);
	}
	if (parms->copiousCalls > 0) {
	    long n = parms->sendLen + parms->recvLen;
	    double kbps;
	    int b;
	    kbps = (double)(parms->copiousCalls * n) / (interval * 1000.0);
	    b = kbps + 0.5;
#if 0
	    I just cannot get printing of floats to work on the pmax !
		!!!printf("%g %d %d %d\n", (float)kbps, b);
	    printf("%g %d %d %d\n", kbps, b);
	    fprintf(stdout, "%g %d %d\n", kbps, b);
	    {
		char buf[100];
		buf[sizeof(buf) - 1] = 0;
		sprintf(buf, "%g %d %d\n", kbps, b);
		assert(buf[sizeof(buf) - 1] == 0);
		printf("%s", buf);
	    }
#endif
	    printf
		("For %lu copious calls, %lu send + %lu recv = %lu bytes each: %d kbytes/sec\n",
		 parms->copiousCalls, parms->sendLen, parms->recvLen, n, b);
#if 0
	    printf("%g\n", kbps);
#endif
	}
    }
    return 0;
}
Esempio n. 29
0
JSInt64
PRMJ_Now(void)
{
#ifdef XP_OS2
    JSInt64 s, us, ms2us, s2us;
    struct timeb b;
#endif
#ifdef XP_WIN
    JSInt64 s, us,
    win2un = JSLL_INIT(0x19DB1DE, 0xD53E8000),
    ten = JSLL_INIT(0, 10);
    FILETIME time, midnight;
#endif
#if defined(XP_UNIX) || defined(XP_BEOS)
    struct timeval tv;
    JSInt64 s, us, s2us;
#endif /* XP_UNIX */

#ifdef XP_OS2
    ftime(&b);
    JSLL_UI2L(ms2us, PRMJ_USEC_PER_MSEC);
    JSLL_UI2L(s2us, PRMJ_USEC_PER_SEC);
    JSLL_UI2L(s, b.time);
    JSLL_UI2L(us, b.millitm);
    JSLL_MUL(us, us, ms2us);
    JSLL_MUL(s, s, s2us);
    JSLL_ADD(s, s, us);
    return s;
#endif
#ifdef XP_WIN
    /* The windows epoch is around 1600. The unix epoch is around 1970.
       win2un is the difference (in windows time units which are 10 times
       more precise than the JS time unit) */
    GetSystemTimeAsFileTime(&time);
    /* Win9x gets confused at midnight
       http://support.microsoft.com/default.aspx?scid=KB;en-us;q224423
       So if the low part (precision <8mins) is 0 then we get the time
       again. */
    if (!time.dwLowDateTime) {
        GetSystemTimeAsFileTime(&midnight);
        time.dwHighDateTime = midnight.dwHighDateTime;
    }
    JSLL_UI2L(s, time.dwHighDateTime);
    JSLL_UI2L(us, time.dwLowDateTime);
    JSLL_SHL(s, s, 32);
    JSLL_ADD(s, s, us);
    JSLL_SUB(s, s, win2un);
    JSLL_DIV(s, s, ten);
    return s;
#endif

#if defined(XP_UNIX) || defined(XP_BEOS)
#ifdef _SVID_GETTOD   /* Defined only on Solaris, see Solaris <sys/types.h> */
    gettimeofday(&tv);
#else
    gettimeofday(&tv, 0);
#endif /* _SVID_GETTOD */
    JSLL_UI2L(s2us, PRMJ_USEC_PER_SEC);
    JSLL_UI2L(s, tv.tv_sec);
    JSLL_UI2L(us, tv.tv_usec);
    JSLL_MUL(s, s, s2us);
    JSLL_ADD(s, s, us);
    return s;
#endif /* XP_UNIX */
}
Esempio n. 30
0
int
write_local_sound(unsigned char* samples) {
	int i;
	static bool do_once = true;
	static int in_count = 0;
	int insert = 0;

  if (do_once)
	{
		if (in_count++ > alsa_cb.thread_buffer_time)
			do_once = false;
			if (in_count > alsa_cb.thread_buffer_time / 2
				&& in_count < alsa_cb.thread_buffer_time)
			return 0;
	}

	for(i = 8; i < 512; i += 8) {
		//bytes are L,R,I,Q skip the I,Q
		alsa_cb.buffer[insert++] = samples[i];     //left
		alsa_cb.buffer[insert++] = samples[i + 1];
		alsa_cb.buffer[insert++] = samples[i + 2]; //right
		alsa_cb.buffer[insert++] = samples[i + 3];
	}

	for(i = 520; i < 1024; i += 8) {
		alsa_cb.buffer[insert++] = samples[i];
		alsa_cb.buffer[insert++] = samples[i + 1];
		alsa_cb.buffer[insert++] = samples[i + 2];
		alsa_cb.buffer[insert++] = samples[i + 3];
	}

	alsa_write(alsa_cb.buffer, 504);

#if 0 // test the audio sample rate
	{
  struct timeb start_time;
  struct timeb end_time;
	static int sample_count = 0;
	static float rate = 0.0;
	static float rate_count = 0.0;

		sample_count+=504;
		if(sample_count >= 48000) {

			ftime(&end_time);

			// skip the 1st one, it's bogus
			if (0.0 == rate_count) {
				rate_count = 1;
				sample_count = 0;
				ftime(&start_time);
				return 0;
			}

			rate += (float)((sample_count*1000/4)
				/(((end_time.time*1000)+end_time.millitm)-
				((start_time.time*1000)+start_time.millitm)));
			printf("sample rate avg: %.1f/sec\n", rate / rate_count);
			sample_count=0;
			rate_count += 1.0;
			ftime(&start_time);
		}
	}
#endif

	return 0;
}