static int SecureClock_GetTime(int sid, lgoem_dev_rtc_type *time)
{
    int sec;
    int cur_sec;

    if (!checkPriv()) return 0; // no privilege
    if (!android::init()) return 0; // binder error

    if (!getCurrentTime(&cur_sec)) cur_sec = -1; // get current time as sec
    sec = android::gService->GetTime(sid, cur_sec); // get secure time as sec

    if (sec < 0) return 0;

    rtc_time_to_lg_tm(sec, time);

    return 1;
}
Esempio n. 2
0
// 获取开辟进程数和split词表文件时的时间戳等其他参数,并生成
int getExtraArgs()
{
    // 获取词表文件的大小
    // 词表文件名:g_pConf->pDictPath/g_pArgs->pDictName
    char pTmpName[MAX_NAME];
    sprintf(pTmpName, "%s%s", g_pConf->pDictPath, g_pArgs->pDictName);

    struct stat statBuffer;
    if (Stat(pTmpName, &statBuffer) != 0) {
        return -1;
    }
    // 文件字节大小
    int iFileByte = statBuffer.st_size;
    const int TMP_SIZE = 10485760; // 10M
    int iFileNum = iFileByte / TMP_SIZE + 1; // 向上取整
    if (iFileNum > 10) {
        iFileNum = 10;    // 最多开辟10个线程
    }

    g_pArgs->iThreadNum = iFileNum; // 赋值给全局线程数
    int iPerSize = iFileByte / iFileNum + 5000; // split -C iPerSize -d -a 1 DictName dict_,加5000为了向上取整,避免剩余的字节数单独生成一个文件。

    char pStrTime[MAX_NAME];
    getCurrentTime(pStrTime);
    strcpy(g_pArgs->pStrTimestamp, pStrTime);  // 赋值给全局时间戳名

    // 创建./dict/timestamp文件夹
    sprintf(pTmpName, "%s%s", g_pConf->pDictPath, g_pArgs->pStrTimestamp);
    checkDataPath(pTmpName);

    // check res file dir exist or not. if not exist, create it.
    // 创建./res/
    sprintf(pTmpName, "%s", g_pConf->pResPath);
    checkDataPath(pTmpName);
    sprintf(pTmpName, "%s%s", g_pConf->pResPath, g_pArgs->pStrTimestamp);
    checkDataPath(pTmpName);
    // 创建时间戳下的online、offline和diff_ret文件夹
    sprintf(pTmpName, "%s%s/%s", g_pConf->pResPath, g_pArgs->pStrTimestamp, "online");
    checkDataPath(pTmpName);
    sprintf(pTmpName, "%s%s/%s", g_pConf->pResPath, g_pArgs->pStrTimestamp, "offline");
    checkDataPath(pTmpName);
    sprintf(pTmpName, "%s%s/%s", g_pConf->pResPath, g_pArgs->pStrTimestamp, "diff_ret");
    checkDataPath(pTmpName);

    return splitDictFile(iPerSize);
}
Esempio n. 3
0
void TouchTest::touchEnded(cocos2d::Touch *touch, cocos2d::Event *event)
{
	isTouch = false;
	pressTimes = 0;
	this->unschedule(schedule_selector(TouchTest::updatelongprogress));

	//如果刚完成长按事件 则把按下次数清零 长按状态置空 直接返回 不继续执行  
	if (m_longProgress) {
		touchCounts = 0;
		m_longProgress = false;

		return;
	}

	m_endPoint = touch->getLocation();

	long long endTime = getCurrentTime();

	long long timeDis = endTime - m_startTime;

	//E_SWIP_DIR dir = GetSwipDir(m_startPoint, m_endPoint, timeDis);

//	if (dir != E_INVAILD) {
	//	onSwip(m_startPoint, m_endPoint, dir);
//		return;
//	}

	//做连击判断  
	if (isMoved) {
		isMoved = false;
		return;
	}
	if (touchCounts == 2) {
	//	onThreeClick();
		touchCounts = 0;
	}
	else if (touchCounts == 1) {
		this->scheduleOnce(schedule_selector(TouchTest::updateDoubleDelay), 0.25);
		touchCounts++;
	}
	else if (touchCounts == 0) {
		this->scheduleOnce(schedule_selector(TouchTest::updateSingleDelay), 0.25);
		touchCounts++;
	}
}
Esempio n. 4
0
	bool SignalSafeSemaphore::tryEnter(const int seconds, int milliseconds)
	{
		// Return true in case of success
		milliseconds += seconds * 1000;
		if (milliseconds == 0)
		{
			// Instant try
			do {
				if (sem_trywait(sem) != -1)
					return true;
			} while (errno == EINTR);
			if (errno == EAGAIN)
				return false;
			system_call_failed::raise("sem_trywait");
		}
		if (milliseconds < 0)
		{
			// Unlimited wait, like enter()
			do {
				if (sem_wait(sem) != -1)
					return true;
			} while (errno == EINTR);
			system_call_failed::raise("sem_wait");
		}
		// Wait with timeout
		timespec timeout = getCurrentTime();
		timeout.tv_sec += milliseconds / 1000;
		timeout.tv_nsec += (milliseconds % 1000) * 1000000;
		timeout.tv_sec += (timeout.tv_nsec / 1000000000l);
		timeout.tv_nsec %= 1000000000l;
		int errcode = 0;
		do {
			int rc = sem_timedwait(sem, &timeout);
			if (rc == 0)
				return true;
			// fix for CORE-988, also please see
			// http://carcino.gen.nz/tech/linux/glibc_sem_timedwait_errors.php
			errcode = rc > 0 ? rc : errno;
		} while (errcode == EINTR);
		if (errcode == ETIMEDOUT) {
			return false;
		}
		system_call_failed::raise("sem_timedwait", errcode);
		return false;	// avoid warnings
	}
Esempio n. 5
0
Npc::Npc(const Texture::Name texture, KillCallback killCallback, float speed) {
	_sprite = TileSprite::create(TextureAtlas::Loader(texture, 4, 4), 0, 0, 11);
	_map = NULL;
	_killCallback = killCallback;
	_lastPosition = 0.0f;
	_physSize = 0;
	_positionOffset = 0.0f;

	_speedMultip = speed >= 30 ? speed = 29 : (speed < 0 ? speed = 0 : speed);

	_lastMoveTime = getCurrentTime();
	_moveDirection = 0;

	for(int i = 0; i < 4; i++) {
		_moveAnimation[i].frames = NULL;
		_moveAnimation[i].framesCount = 0;
	}
}
void COpcAdapter::SetMTCTagValue(std::string tag, std::string value)
{
#if 1
	Agent * agent = _agentconfig->getAgent();
	Device *pDev = agent->getDeviceByName(_device);
	DataItem *di = pDev->getDeviceDataItem(tag);
	if (di != NULL)
	{
		std::string time = getCurrentTime(GMT_UV_SEC);
		agent->addToBuffer(di, value, time);
	}
	else
	{
		LOGONCE GLogger.LogMessage(StdStringFormat("(%s) Could not find data item: %s  \n",  _device.c_str(), tag.c_str()));
	}

#endif
}
Esempio n. 7
0
int getIdentityStringByTime(char *identityString)
{
    static char timeBuf[TIMESTRING_BUFFER_SIZE];
    static char dateBuf[TIMESTRING_BUFFER_SIZE];

    long long curTime;
    struct tm tmobj;
    tmobj = getCurrentTime();
    curTime = getCurrentTimerCounter();

    sprintf_s(identityString, IDENTITYSTRING_BUFFER_SIZE, 
        "%04d%02d%02d-%02d%02d%02d-%lld", 
        (1900 + tmobj.tm_year), (1 + tmobj.tm_mon), tmobj.tm_mday,
        tmobj.tm_hour, tmobj.tm_min, tmobj.tm_sec,
        curTime);

    return 1;
}
Esempio n. 8
0
static int
do_comm_select(int msec)
{
    int num, saved_errno;
    struct timeval tv;
    fd_set readfds;
    fd_set writefds;
    fd_set errfds;
    int fd;

    if (nreadfds + nwritefds == 0) {
	assert(shutting_down);
	return COMM_SHUTDOWN;
    }
    memcpy(&readfds, &global_readfds, sizeof(fd_set));
    memcpy(&writefds, &global_writefds, sizeof(fd_set));
    memcpy(&errfds, &global_writefds, sizeof(fd_set));
    tv.tv_sec = msec / 1000;
    tv.tv_usec = (msec % 1000) * 1000;
    statCounter.syscalls.selects++;
    num = select(Biggest_FD + 1, &readfds, &writefds, &errfds, &tv);
    saved_errno = errno;
    getCurrentTime();
    debug(5, 5) ("do_comm_select: %d fds ready\n", num);
    if (num < 0) {
	if (ignoreErrno(saved_errno))
	    return COMM_OK;

	debug(5, 1) ("comm_select: select failure: %s\n", xstrerror());
	return COMM_ERROR;
    }
    statHistCount(&statCounter.select_fds_hist, num);

    if (num == 0)
	return COMM_TIMEOUT;

    for (fd = 0; fd <= Biggest_FD; fd++) {
	int read_event = FD_ISSET(fd, &readfds);
	int write_event = FD_ISSET(fd, &writefds) || FD_ISSET(fd, &errfds);
	if (read_event || write_event)
	    comm_call_handlers(fd, read_event, write_event);
    }
    return COMM_OK;
}
Esempio n. 9
0
U32 postEvent(SimObject *destObject, SimEvent* event,U32 time)
{
	AssertFatal(time == -1 || time >= getCurrentTime(),
      "Sim::postEvent() - Event time must be greater than or equal to the current time." );
   AssertFatal(destObject, "Sim::postEvent() - Destination object for event doesn't exist.");

   Mutex::lockMutex(gEventQueueMutex);

   if( time == -1 )
      time = gCurrentTime;

   event->time = time;
   event->startTime = gCurrentTime;
   event->destObject = destObject;

   if(!destObject)
   {
      delete event;

      Mutex::unlockMutex(gEventQueueMutex);

      return InvalidEventId;
   }
   event->sequenceCount = gEventSequence++;
   SimEvent **walk = &gEventQueue;
   SimEvent *current;
   
   while((current = *walk) != NULL && (current->time < event->time))
      walk = &(current->nextEvent);
   
   // [tom, 6/24/2005] This ensures that SimEvents are dispatched in the same order that they are posted.
   // This is needed to ensure Con::threadSafeExecute() executes script code in the correct order.
   while((current = *walk) != NULL && (current->time == event->time))
      walk = &(current->nextEvent);
   
   event->nextEvent = current;
   *walk = event;

   U32 seqCount = event->sequenceCount;

   Mutex::unlockMutex(gEventQueueMutex);

   return seqCount;
}
Esempio n. 10
0
void File::readFile(int fd, char* buffer, int size)//,TableManager& tm , FileSystem& fs )
{
	TableManager* t = TableManager::getInstance();
	TableManager& tm = *t;

	FileSystem* f = FileSystem::getInstance();
	FileSystem& fs = *f;

	InodeElement* inodeE = ((InodeElement*)tm.getElement(INODET, fd));
	Inode inode = inodeE->inode;

	int blocks = atoi(inode.blocks);
	int* dataIdx = new int[blocks];
	translateCharArrToIntArr(inode.dataBlockList, dataIdx, blocks);

	int filePointer = ((SFTElement*)tm.getElement(SFT, fd))->file_pointer;// (FT)   getFilePoint( fd ) fd�� ����Ű�� �ý����������̺��� ���������͸� �޾ƿ´�

																		  // �ϳ��� data���� �� �����ͺ��� �л��� �͵��� ��ħ
	string data = "";
	for (int i = 0; i < blocks; i++)
	{
		char* blockData;
		fs.readFS(dataIdx[i], blockData);
		data += blockData;
	}

	int fileSize = data.length();
	if (size == 0) // ���ϳ��� ��ü ���� �� ���
		size = fileSize;
	else if (fileSize < size) // ����ũ�Ⱑ ����ڰ� ���� size���� ū ���, ���� ���Ͽ� ������ ���븸ŭ���� ������ ����
		size = fileSize;

	buffer = new char[size];

	std::strcpy(buffer, data.substr(filePointer, size).c_str());
	tm.updateFilePointer(fd, filePointer + size);

	getCurrentTime(inode.time);

	// (FT)   Inode Block �� time(���� ������ ���ٽð�) ����
	tm.updateInode(fd, inode);
	// (FS)   inode ����
	fs.updateInode_readFile(inodeE->inode_number, inode);
}//readFile
Esempio n. 11
0
static void sineSurf_renderingFunction(cubeFrameBuf *buf)
{
	static systemTime_t lastUpdateTime = 0U;
	systemTime_t curtime = getSystemTimeUS();

		if (0 == lastUpdateTime)
		{
			lastUpdateTime = curtime;
		}

		if (lastUpdateTime + SINE_SURF_UPDATE_INTERVAL_US < curtime)
		{
			lastUpdateTime = getCurrentTime();

			g_phase += 2.f * M_PI / (SINE_SURF_ROUND_TIME_US / SINE_SURF_UPDATE_INTERVAL_US);

			sineSurf_draw(buf);
		}
}
Esempio n. 12
0
int main(int argc, char **argv){
	setbuf(stdout,NULL);
	printf("Start\n");

	signal(SIGINT, StopServer);

	//初始化网络事件循环
	g_event_loop = aeCreateEventLoop(1024*10);
	
	long int start_time = getCurrentTime();
	/*//设置监听事件
	int i;
	for(i=0; i<10; i++){
		int fd = anetTcpConnect(NULL, argv[1], atoi(argv[2]));
		if( ANET_ERR == fd ){
			fprintf(stderr, "connect error: %s\n", PORT, NULL);
		}
		if(anetNonBlock(NULL, fd) == ANET_ERR){
			fprintf(stderr, "set nonblock error: %d\n", fd);
		}
		
		
		WriteHandler(g_event_loop, fd, NULL, 0);
	}*/

	
	//设置定时事件
	aeCreateTimeEvent(g_event_loop, 5000, PrintTimer, NULL, NULL);

	//开启事件循环
	aeMain(g_event_loop);

	//删除事件循环
	aeDeleteEventLoop(g_event_loop);

	/*printf("End\n");
	long int end_time = getCurrentTime();
	double elapsed = (double)(end_time-start_time);
	printf("test_time : %0.2f s\n", elapsed/1000);
	printf("total_req : %d\n", total_req);
	printf("total_res : %d\n", total_res);*/
	return 0;
}
static int
do_comm_select(int msec)
{
    int num;
    int i;

    if (nfds == 0) {
	assert(shutting_down);
	return COMM_SHUTDOWN;
    }
    statCounter.syscalls.selects++;
    num = poll(pfds, nfds, msec);
    if (num < 0) {
	getCurrentTime();
	if (ignoreErrno(errno))
	    return COMM_OK;

	debug(5, 1) ("comm_select: poll failure: %s\n", xstrerror());
	return COMM_ERROR;
    }
    statHistCount(&statCounter.select_fds_hist, num);

    if (num == 0)
	return COMM_TIMEOUT;

    for (i = nfds - 1; num > 0 && i >= 0; i--) {
	struct pollfd *pfd = &pfds[i];
	short read_event, write_event;

	if (!pfd->revents)
	    continue;

	read_event = pfd->revents & (POLLRDNORM | POLLIN | POLLHUP | POLLERR);
	write_event = pfd->revents & (POLLWRNORM | POLLOUT | POLLHUP | POLLERR);

	pfd->revents = 0;

	comm_call_handlers(pfd->fd, read_event, write_event);
	num--;
    }

    return COMM_OK;
}
Esempio n. 14
0
static void	report(struct timeval *startTime, unsigned long bytesSent)
{
	struct timeval	endTime;
	unsigned long	usec;
	float		rate;

	getCurrentTime(&endTime);
	if (endTime.tv_usec < startTime->tv_usec)
	{
		endTime.tv_sec--;
		endTime.tv_usec += 1000000;
	}

	usec = ((endTime.tv_sec - startTime->tv_sec) * 1000000)
			+ (endTime.tv_usec - startTime->tv_usec);
	printf("Bytes sent = %lu, usec elapsed = %lu.\n", bytesSent, usec);
	rate = (float) (8 * bytesSent) / (float) (usec / 1000000);
	printf("Sending %7.2f bits per second.\n", rate);
}
Esempio n. 15
0
GAE_Clock_t* GAE_Clock_create(void) {
	GAE_Clock_t* clock = malloc(sizeof(GAE_Clock_t));
	GAE_Clock_Linux_t* linuxClock = malloc(sizeof(GAE_Clock_Linux_t));
	struct timespec time;

	clock->deltaTime = 0.0F;
	clock->currentTime = 0.0F;
	clock->isPaused = GAE_FALSE;
	clock->platformData = linuxClock;

	clock_gettime(CLOCK_MONOTONIC, &time);
	linuxClock->startTime = getCurrentTime(&time);
	linuxClock->currentTime = linuxClock->startTime;
	linuxClock->currentDelta = 0.0;
	linuxClock->pausedTime = 0.0;


	return clock;
}
Esempio n. 16
0
void NetInterface::sendConnectRequest(NetConnection *conn)
{
   TNLLogMessageV(LogNetInterface, ("Sending Connect Request"));
   PacketStream out;
   ConnectionParameters &theParams = conn->getConnectionParameters();

   out.write(U8(ConnectRequest));
   theParams.mNonce.write(&out);
   theParams.mServerNonce.write(&out);
   out.write(theParams.mClientIdentity);
   out.write(theParams.mPuzzleDifficulty);
   out.write(theParams.mPuzzleSolution);

   U32 encryptPos = 0;

   if(out.writeFlag(theParams.mUsingCrypto))
   {
      out.write(theParams.mPrivateKey->getPublicKey());
      encryptPos = out.getBytePosition();
      out.setBytePosition(encryptPos);
      out.write(SymmetricCipher::KeySize, theParams.mSymmetricKey);
   }
   out.writeFlag(theParams.mDebugObjectSizes);
   out.write(conn->getInitialSendSequence());
   out.writeString(conn->getClassName());
   conn->writeConnectRequest(&out);

   if(encryptPos)
   {
      // if we're using crypto on this connection,
      // then write a hash of everything we wrote into the packet
      // key.  Then we'll symmetrically encrypt the packet from
      // the end of the public key to the end of the signature.

      SymmetricCipher theCipher(theParams.mSharedSecret);
      out.hashAndEncrypt(NetConnection::MessageSignatureBytes, encryptPos, &theCipher);      
   }

   conn->mConnectSendCount++;
   conn->mConnectLastSendTime = getCurrentTime();

   out.sendto(mSocket, conn->getNetAddress());
}
Esempio n. 17
0
void Individual::handle_inherit( const ClothoEvent * evt ) {
    const InheritEvent * ie = static_cast< const InheritEvent * >( evt );

    if(m_prop->getEOL() != SystemClock::POSITIVE_INFINITY ) {
        m_prop->reset();
    }

    m_prop->inheritFrom( ie->getSender(), ie->getParentSex(), ie->getGamete() );

    if( m_prop->getFather() != UNSET_ID && m_prop->getMother() != UNSET_ID ) {
        event::vtime_t bday = evt->getReceived();
        bday = ((bday / LIFE_CYCLE_PADDING) + 1) * LIFE_CYCLE_PADDING;

        BirthEvent * be = BirthEvent::getOrCreate();
        be->init( getCurrentTime(), bday, this->getSystemID(), this->getSystemID(), getNextEventID(), m_prop->getSex() );
//        handle_birth( evt );
        sendEvent( be );
    }
}
Esempio n. 18
0
void MetricBackend_opengl::beginPass() {
    if (curPass == 1) {
        for (int i = 0; i < QUERY_BOUNDARY_LIST_END; i++) {
            for (auto &m : metrics) {
                if (m.enabled[i]) m.profiled[i] = true;
            }
        }
        // profile frames in first pass
        if (twoPasses) {
            if (!supportsTimestamp) {
                metrics[METRIC_GPU_DURATION].profiled[QUERY_BOUNDARY_DRAWCALL] = false;
                metrics[METRIC_GPU_DURATION].profiled[QUERY_BOUNDARY_CALL] = false;
            }
            metrics[METRIC_GPU_PIXELS].profiled[QUERY_BOUNDARY_DRAWCALL] = false;
            metrics[METRIC_GPU_PIXELS].profiled[QUERY_BOUNDARY_CALL] = false;
        }
    }
    else if (curPass == 2) {
        for (int i = 0; i < QUERY_BOUNDARY_LIST_END; i++) {
            for (auto &m : metrics) {
                m.profiled[i] = false;
            }
        }
        // profile calls/draw calls in second pass
        if (!supportsTimestamp) {
            if (metrics[METRIC_GPU_DURATION].enabled[QUERY_BOUNDARY_DRAWCALL]) {
                metrics[METRIC_GPU_DURATION].profiled[QUERY_BOUNDARY_DRAWCALL] = true;
            }
            if (metrics[METRIC_GPU_DURATION].enabled[QUERY_BOUNDARY_CALL]) {
                metrics[METRIC_GPU_DURATION].profiled[QUERY_BOUNDARY_CALL] = true;
            }
        }
        if (metrics[METRIC_GPU_PIXELS].enabled[QUERY_BOUNDARY_DRAWCALL]) {
            metrics[METRIC_GPU_PIXELS].profiled[QUERY_BOUNDARY_DRAWCALL] = true;
        }
        if (metrics[METRIC_GPU_PIXELS].enabled[QUERY_BOUNDARY_CALL]) {
            metrics[METRIC_GPU_PIXELS].profiled[QUERY_BOUNDARY_CALL] = true;
        }
    }
    // setup times
    cpuTimeScale = 1.0E9 / getTimeFrequency();
    baseTime = getCurrentTime() * cpuTimeScale;
}
Esempio n. 19
0
void slog(int level, const char *pszFormat, ...) {
	char buf[LOGBUFSIZE] = "";
	if (level <= _logLevel) {

		// calculate the timestamp - dd/mm/yyyy hh:mm:ss
	    char timestamp[20];
		struct tm now;
	    getCurrentTime(&now);
	    snprintf(timestamp, 20, "%02d/%02d/%04d %02d:%02d:%02d", now.tm_mday, now.tm_mon + 1, now.tm_year+1900, now.tm_hour, now.tm_min, now.tm_sec);

		va_list arglist;
		va_start(arglist, pszFormat);
		vsnprintf(&buf[strlen(buf)], LOGBUFSIZE - strlen(buf) - 1, pszFormat, arglist);
		va_end(arglist);

		fprintf(stdout, "(%d - %s): %s", getpid(), timestamp, buf);
		flushLog();
	}
}
Esempio n. 20
0
float PerfRenderer::computeFPS()
{
	// Calculate frame rate
	
	float currTime=getCurrentTime();
	
	fpsTimes[fpsIndex]=currTime-lastTime;
	fpsIndex=(fpsIndex+1)%FPS_AVG_FRAMES;
	
	float avgTime=0.0f;
	for(unsigned int i=0;i<FPS_AVG_FRAMES;i++)
		avgTime+=fpsTimes[i];

	avgTime/=FPS_AVG_FRAMES;
	
	lastTime=currTime;

	return 1.0f/avgTime;
}
Esempio n. 21
0
void HTTPConnector::connectSuccess() noexcept {
  if (!cb_) {
    return;
  }

  folly::SocketAddress localAddress;
  folly::SocketAddress peerAddress;
  socket_->getLocalAddress(&localAddress);
  socket_->getPeerAddress(&peerAddress);

  std::unique_ptr<HTTPCodec> codec;

  transportInfo_.acceptTime = getCurrentTime();
  if (transportInfo_.ssl) {
    AsyncSSLSocket* sslSocket = dynamic_cast<AsyncSSLSocket*>(socket_.get());

    const char* npnProto;
    unsigned npnProtoLen;
    sslSocket->getSelectedNextProtocol(
      reinterpret_cast<const unsigned char**>(&npnProto), &npnProtoLen);

    transportInfo_.sslNextProtocol =
        std::make_shared<std::string>(npnProto, npnProtoLen);
    transportInfo_.sslSetupTime = millisecondsSince(connectStart_);
    transportInfo_.sslCipher = sslSocket->getNegotiatedCipherName() ?
      std::make_shared<std::string>(sslSocket->getNegotiatedCipherName()) :
      nullptr;
    transportInfo_.sslVersion = sslSocket->getSSLVersion();
    transportInfo_.sslResume = wangle::SSLUtil::getResumeState(sslSocket);

    codec = makeCodec(*transportInfo_.sslNextProtocol, forceHTTP1xCodecTo1_1_);
  } else {
    codec = makeCodec(plaintextProtocol_, forceHTTP1xCodecTo1_1_);
  }

  HTTPUpstreamSession* session = new HTTPUpstreamSession(
    timeoutSet_,
    std::move(socket_), localAddress, peerAddress,
    std::move(codec), transportInfo_, nullptr);

  cb_->connectSuccess(session);
}
Esempio n. 22
0
void MetricBackend_opengl::endQuery(QueryBoundary boundary) {
    if (queryInProgress[boundary]) {
        // CPU related
        if (metrics[METRIC_CPU_DURATION].profiled[boundary])
        {
            cpuEnd[boundary] = getCurrentTime();
            int64_t time = (cpuEnd[boundary] - cpuStart[boundary]) * cpuTimeScale;
            data[METRIC_CPU_DURATION][boundary]->addData(boundary, time);
        }
        if (metrics[METRIC_CPU_VSIZE_DURATION].profiled[boundary])
        {
            vsizeEnd[boundary] = os::getVsize();
            int64_t time = vsizeEnd[boundary] - vsizeStart[boundary];
            data[METRIC_CPU_VSIZE_DURATION][boundary]->addData(boundary, time);
        }
        if (metrics[METRIC_CPU_RSS_DURATION].profiled[boundary])
        {
            rssEnd[boundary] = os::getRss();
            int64_t time = rssEnd[boundary] - rssStart[boundary];
            data[METRIC_CPU_RSS_DURATION][boundary]->addData(boundary, time);
        }
        // GPU related
        if (glQueriesNeeded[boundary]) {
            std::array<GLuint, QUERY_LIST_END> &query = queries[boundary].back();
            if (metrics[METRIC_GPU_DURATION].profiled[boundary] && supportsTimestamp) {
                // GL_TIME_ELAPSED cannot be used in nested queries
                // so prefer this if timestamps are supported
                glQueryCounter(query[QUERY_GPU_DURATION], GL_TIMESTAMP);
            }
            if (metrics[METRIC_GPU_PIXELS].profiled[boundary]) {
                glEndQuery(GL_SAMPLES_PASSED);
            }
        }
        queryInProgress[boundary] = false;
    }
    // DRAWCALL is a CALL
    if (boundary == QUERY_BOUNDARY_DRAWCALL) endQuery(QUERY_BOUNDARY_CALL);
    // clear queries after each frame
    if (boundary == QUERY_BOUNDARY_FRAME && glQueriesNeededAnyBoundary) {
        processQueries();
    }
}
Esempio n. 23
0
void NetInterface::sendPunchPackets(NetConnection *conn)
{
   ConnectionParameters &theParams = conn->getConnectionParameters();
   PacketStream out;
   out.write(U8(Punch));

   if(theParams.mIsInitiator)
      theParams.mNonce.write(&out);
   else
      theParams.mServerNonce.write(&out);

   U32 encryptPos = out.getBytePosition();
   out.setBytePosition(encryptPos);

   if(theParams.mIsInitiator)
      theParams.mServerNonce.write(&out);
   else
   {
      theParams.mNonce.write(&out);
      if(out.writeFlag(mRequiresKeyExchange || (theParams.mRequestKeyExchange && !mPrivateKey.isNull())))
      {
         if(out.writeFlag(theParams.mRequestCertificate && !mCertificate.isNull()))
            out.write(mCertificate);
         else
            out.write(mPrivateKey->getPublicKey());
      }
   }
   SymmetricCipher theCipher(theParams.mArrangedSecret);
   out.hashAndEncrypt(NetConnection::MessageSignatureBytes, encryptPos, &theCipher);

   for(S32 i = 0; i < theParams.mPossibleAddresses.size(); i++)
   {
      out.sendto(mSocket, theParams.mPossibleAddresses[i]);

      TNLLogMessageV(LogNetInterface, ("Sending punch packet (%s, %s) to %s",
         ByteBuffer(theParams.mNonce.data, Nonce::NonceSize).encodeBase64()->getBuffer(),
         ByteBuffer(theParams.mServerNonce.data, Nonce::NonceSize).encodeBase64()->getBuffer(),
         theParams.mPossibleAddresses[i].toString()));
   }
   conn->mConnectSendCount++;
   conn->mConnectLastSendTime = getCurrentTime();
}
Esempio n. 24
0
void
beginProfile(trace::Call &call, bool isDraw) {
    glretrace::Context *currentContext = glretrace::getCurrentContext();

    /* Create call query */
    CallQuery query;
    query.isDraw = isDraw;
    query.call = call.no;
    query.sig = call.sig;
    query.program = currentContext ? currentContext->activeProgram : 0;

    glGenQueries(NUM_QUERIES, query.ids);

    /* GPU profiling only for draw calls */
    if (isDraw) {
        if (retrace::profilingGpuTimes) {
            if (supportsTimestamp) {
                glQueryCounter(query.ids[GPU_START], GL_TIMESTAMP);
            }

            glBeginQuery(GL_TIME_ELAPSED, query.ids[GPU_DURATION]);
        }

        if (retrace::profilingPixelsDrawn) {
            glBeginQuery(GL_SAMPLES_PASSED, query.ids[OCCLUSION]);
        }
    }

    callQueries.push_back(query);

    /* CPU profiling for all calls */
    if (retrace::profilingCpuTimes) {
        CallQuery& query = callQueries.back();
        query.cpuStart = getCurrentTime();
    }

    if (retrace::profilingMemoryUsage) {
        CallQuery& query = callQueries.back();
        query.vsizeStart = os::getVsize();
        query.rssStart = os::getRss();
    }
}
Esempio n. 25
0
glm::quat CameraRig::predict(float time) {
    long long clock_time = getCurrentTime();
    float time_diff = (clock_time - rotation_sensor_data_.time_stamp())
            / 1000000000.0f;

    glm::vec3 axis = rotation_sensor_data_.gyro();
    float angle = glm::length(axis);

    if (angle != 0.0f) {
        axis /= angle;
    }
    angle *= (time + time_diff) * 180.0f / M_PI;

    glm::quat rotation = rotation_sensor_data_.quaternion()
            * glm::angleAxis(angle, axis);

    glm::quat transform_rotation = complementary_rotation_ * rotation;

    return transform_rotation;
}
Esempio n. 26
0
void Model::setup()
{
    registerBuiltinModules();

    // initialize theRootSystem
    theRootSystem = createSystem( "System" );
    theRootSystem->setID( "/" );
    theRootSystem->setName( "The Root System" );
    // super system of the root system is itself.
    theRootSystem->setSuperSystem( theRootSystem );

    // initialize theSystemStepper
    theSystemStepper.setModel( this );
    theSystemStepper.setID( "___SYSTEM" );
    theScheduler.addEvent(
        StepperEvent( getCurrentTime() + theSystemStepper.getStepInterval(),
                      &theSystemStepper ) );

    theLastStepper = &theSystemStepper;
}
Esempio n. 27
0
void
rel_destroy (rel_t *r)
{
  // printf("rel_destroy\n");
  uint32_t curTime = getCurrentTime();
  fprintf(stderr, "RECEIVED TIME: %u SENT TIME: %u\n", curTime, r->startTime);
  conn_destroy (r->c);

  /* Free any other allocated memory here */
  int i;
  for (i = 0; i < r->ssThresh; i++) {
    free(r->sentPackets[i]->packet);
    free(r->sentPackets[i]);
    free(r->recvPackets[i]->packet);
    free(r->recvPackets[i]);
  }
  free(r->sentPackets);
  free(r->recvPackets);
  free(r);
}
Esempio n. 28
0
int howManyTasks(const char *file)
{
    char curTime[30];
    FILE *fp = fopen(file,"r");
    if (fp == NULL) {
        getCurrentTime(curTime);
        printf("[%s] Process ID #%d did not terminate successfully.\n", curTime, getpid());
        exit(-1);
    }
    char ch;
    int taskCount = 0;
    while(!feof(fp))
    {
      ch = fgetc(fp);
      if(ch == '\n')
        taskCount++;
    }
    close(fp);
    return taskCount - 1;
}
Esempio n. 29
0
ThreadState::~ThreadState() {
	// if the System.exit method is used to shut down the VM,
	// we'll have a non-empty stack frame.
	// just mark the current time as the end time
	while(!callStack.empty()) {
		jlong endTime = getCurrentTime();
		StackFrame frame = callStack.top();
		callStack.pop();
		writeTime(endTime,frame.timeStamp,frame.methodId);
	}

	if(p!=NULL) {
		{
			CLock lock(&threadStateLock);
			threadStates.erase(this);
		}
		delete p;
	}
	p = NULL;
}
Esempio n. 30
0
void LOPuzzle::touchEnded(void * touch, float x, float y)
{
    if (selectedPartsCount>0)
    {
        screenToButtonsPuzzle(x,y);
        if (getCurrentTime()-startTouchTime<0.3 && moveDelta<0.5)
        {
            rotateParts(selectedParts, selectedPartsCount);
        } 
        for (short i = 0;i<selectedPartsCount;i++)
            checkTheConnection(selectedParts[i]);
        
        if (!playConnectSound)
            playDropSound = true;
        
        selectedPartsCount = 0;
        free(selectedParts);
        selectedParts = 0;
    }
}