void patchExpressionFunctionObject::writeTheData(const word &pName,PatchValueExpressionDriver &driver)
{
    Field<T> result(driver.getResult<T>());

    AccumulationCalculation<T> calculator(
        result,
        driver.result().isPoint(),
        driver
    );

    Field<T> results(accumulations_.size());

    forAll(accumulations_,i) {
        const NumericAccumulationNamedEnum::accuSpecification accu=
            accumulations_[i];
        T val=calculator(accu);

        results[i]=val;
        if(verbose()) {
            Info << " " << accu
                << "=" << val;
        }
    }

    if (Pstream::master()) {
        writeTime(pName,time().value());
        writeData(pName,results);
        endData(pName);
    }
}
예제 #2
0
void writeRecord(WriteStream *outFile, uint32 diff, const Event &event, uint32 millis) {
	writeTime(outFile, millis);

	outFile->writeUint32LE(diff);

	outFile->writeUint32LE((uint32)event.type);

	switch (event.type) {
	case EVENT_KEYDOWN:
	case EVENT_KEYUP:
		outFile->writeSint32LE(event.kbd.keycode);
		outFile->writeUint16LE(event.kbd.ascii);
		outFile->writeByte(event.kbd.flags);
		break;
	case EVENT_MOUSEMOVE:
	case EVENT_LBUTTONDOWN:
	case EVENT_LBUTTONUP:
	case EVENT_RBUTTONDOWN:
	case EVENT_RBUTTONUP:
	case EVENT_WHEELUP:
	case EVENT_WHEELDOWN:
	case EVENT_MBUTTONDOWN:
	case EVENT_MBUTTONUP:
		outFile->writeSint16LE(event.mouse.x);
		outFile->writeSint16LE(event.mouse.y);
		break;
	default:
		break;
	}
}
예제 #3
0
void EventRecorder::processMillis(uint32 &millis) {
	uint32 d;
	if (_recordMode == kPassthrough) {
		return;
	}

	g_system->lockMutex(_timeMutex);
	if (_recordMode == kRecorderRecord) {
		d = millis - _lastMillis;
		writeTime(_recordTimeFile, d);

		_recordTimeCount++;
	}

	if (_recordMode == kRecorderPlayback) {
		if (_recordTimeCount > _playbackTimeCount) {
			d = readTime(_playbackTimeFile);

			while ((_lastMillis + d > millis) && (_lastMillis + d - millis > 50)) {
				_recordMode = kPassthrough;
				g_system->delayMillis(50);
				millis = g_system->getMillis();
				_recordMode = kRecorderPlayback;
			}

			millis = _lastMillis + d;
			_playbackTimeCount++;
		}
	}

	_lastMillis = millis;
	g_system->unlockMutex(_timeMutex);
}
예제 #4
0
void phaseChangeModel::correct
(
    const scalar dt,
    scalarField& availableMass,
    volScalarField& dMass,
    volScalarField& dEnergy
)
{
    if (!active())
    {
        return;
    }

    correctModel
    (
        dt,
        availableMass,
        dMass,
        dEnergy
    );

    latestMassPC_ = sum(dMass.primitiveField());
    totalMassPC_ += latestMassPC_;

    availableMass -= dMass;
    dMass.correctBoundaryConditions();

    if (writeTime())
    {
        scalar phaseChangeMass = getModelProperty<scalar>("phaseChangeMass");
        phaseChangeMass += returnReduce(totalMassPC_, sumOp<scalar>());
        setModelProperty<scalar>("phaseChangeMass", phaseChangeMass);
        totalMassPC_ = 0.0;
    }
}
static void *ca8210_test_int_read_worker(void *arg)
{
	uint8_t rx_buf[512];
	size_t rx_len;
	int i;
	struct timeval timeout;
	timeout.tv_sec = 5;
	timeout.tv_usec = 0;

	/* TODO: while not told to exit? */
	while (1) {

		rx_len = 0;

		FD_ZERO(&rx_block_fd_set);
		FD_SET(DriverFileDescriptor, &rx_block_fd_set);

		//Wait until there is data available to read (or time out after 5 seconds)
		select(DriverFileDescriptor + 1, &rx_block_fd_set, NULL, NULL, &timeout);

		//try to get fresh data
		if(pthread_mutex_trylock(&rx_mutex) == 0){
			rx_len = read(DriverFileDescriptor, rx_buf, 0);

#ifdef USE_LOGFILE
			if (rx_len > 0) {
				pthread_mutex_lock(&file_mutex);
				writeTime(LogFileDescriptor);
				fputs("\r\nReceived Async:",LogFileDescriptor);
				for(i = 0; i < rx_len; i++){
					fprintf(LogFileDescriptor, " %02x", rx_buf[i]);
				}
				fputs("\r\n",LogFileDescriptor);
				pthread_mutex_unlock(&file_mutex);
			}
#endif

			if(rx_len > 0 && (rx_buf[0] & SPI_SYN)){	//Catch unhandled synchronous commands so synchronicity for future commands is not lost
				unhandled_sync_count--;
				assert(unhandled_sync_count >= 0);
				pthread_cond_signal(&unhandled_sync_cond);
			}

			pthread_mutex_unlock(&rx_mutex);
		}

		//If nothing was received this cycle, get something from the queue
		if(rx_len == 0){
			rx_len = pop_from_queue(rx_buf, 512);
		}

		if (rx_len > 0) {
			ca821x_downstream_dispatch(rx_buf, rx_len);
		}
	}

	return NULL;
}
void dumpSwakExpressionFunctionObject::writeTheData(CommonValueExpressionDriver &driver)
{
    Field<T> result=driver.getResult<T>();

    if (Pstream::master()) {
        writeTime(name(),time().value());
        writeData(name(),result);
        endData(name());
    } else {
        Pout << "My data is lost because for dumpSwakExpressionFunctionObject"
            << " only the masters data gets written" << endl;
    }
}
void CmdLogger::Log(int level,const char* base,...)
{
    if(level <= priority && priority >= 0)
    {
        writeTime();
        va_list a_list;
        va_start(a_list,base);
        printf("%*c",indent*indentSize,' ');
        vprintf(base,a_list);
        printf("\n");
        va_end(a_list);
    };
};
void dumpSwakExpressionFunctionObject::writeTheData(CommonValueExpressionDriver &driver)
{
    List<Field<T> > results(Pstream::nProcs());
    results[Pstream::myProcNo()]=driver.getResult<T>();

    Pstream::gatherList(results);

    if (Pstream::master()) {
        writeTime(name(),time().value());
        forAll(results,procNo) {
            writeData(name(),results[procNo]);
        }
        endData(name());
    }
void FileLogger::Log(const char* base, ...)
{
    if(priority >= 0 && logfile != NULL)
    {
        writeTime();
        va_list a_list;
        va_start(a_list,base);
        fprintf(logfile,"%*c",indent*indentSize,' ');
        vfprintf(logfile,base,a_list);
        va_end(a_list);
        fprintf(logfile,"\n");
        fflush(logfile);
    }
};
예제 #10
0
	TIME ActiveSetConservativeCom::GetNextTime(TIME currentTime,
			TIME nextTime) {
		TIME nextEstTime;
		if (nextTime < grantedTime)
			return grantedTime;

		//bool busywait = false;
		bool needToRespond = false;
		bool reIterate = false;

#ifdef DEBUG
		CERR << "Start comm sync currentTime:" << currentTime << " nextTime: " << nextTime << endl;
#endif
		do {

			uint64_t diff = interface->reduceTotalSendReceive();
			if (diff > 0) {
				this->interface->packetLostCalculator(currentTime);
			}
			if(diff==0)
			      this->interface->resetCounters();
			//network unstable, we need to wait!

			TIME minnetworkdelay = interface->reduceNetworkDelay();
			TIME myminNextTime = Infinity;
			TIME minNextTime = (TIME) interface->reduceMinTimeWithSleep(
					myminNextTime, false);
			nextEstTime = minNextTime;
			reIterate = false;
			if (minNextTime == grantedTime) {
				currentTime = convertToMyTime(Integrator::getCurSimMetric(),
						minNextTime);
				currentTime = convertToFrameworkTime(
						Integrator::getCurSimMetric(), currentTime);

				reIterate = true;
			}
		} while (reIterate);

		this->grantedTime = nextEstTime;
#ifdef DEBUG
		CERR << "End comm sync grantedTime:" << nextEstTime;
#endif
#ifdef PROFILE
		writeTime(currentTime);
#endif
		return nextEstTime;

	}
예제 #11
0
bool Foam::functionObjects::yPlus::write(const bool postProcess)
{
    const volScalarField& yPlus =
        obr_.lookupObject<volScalarField>(type());

    Log << type() << " " << name() << " write:" << nl
        << "    writing field " << yPlus.name() << endl;

    yPlus.write();

    writeFiles::write();

    const volScalarField::Boundary& yPlusBf = yPlus.boundaryField();

    const fvMesh& mesh = refCast<const fvMesh>(obr_);
    const fvPatchList& patches = mesh.boundary();

    forAll(patches, patchi)
    {
        const fvPatch& patch = patches[patchi];

        if (isA<wallFvPatch>(patch))
        {
            const scalarField& yPlusp = yPlusBf[patchi];

            const scalar minYplus = gMin(yPlusp);
            const scalar maxYplus = gMax(yPlusp);
            const scalar avgYplus = gAverage(yPlusp);

            if (Pstream::master())
            {
                Log << "    patch " << patch.name()
                    << " y+ : min = " << minYplus << ", max = " << maxYplus
                    << ", average = " << avgYplus << nl;

                writeTime(file());
                file()
                << token::TAB << patch.name()
                    << token::TAB << minYplus
                    << token::TAB << maxYplus
                    << token::TAB << avgYplus
                    << endl;
            }
        }
    }

    return true;
}
예제 #12
0
bool Foam::functionObjects::yPlus::write()
{
    Log << type() << " " << name() << " write:" << nl;

    writeLocalObjects::write();

    logFiles::write();

    const volScalarField& yPlus =
        mesh_.lookupObject<volScalarField>(type());

    const volScalarField::Boundary& yPlusBf = yPlus.boundaryField();
    const fvPatchList& patches = mesh_.boundary();

    forAll(patches, patchi)
    {
        const fvPatch& patch = patches[patchi];

        if (isA<wallFvPatch>(patch))
        {
            const scalarField& yPlusp = yPlusBf[patchi];

            const scalar minYplus = gMin(yPlusp);
            const scalar maxYplus = gMax(yPlusp);
            const scalar avgYplus = gAverage(yPlusp);

            if (Pstream::master())
            {
                Log << "    patch " << patch.name()
                    << " y+ : min = " << minYplus << ", max = " << maxYplus
                    << ", average = " << avgYplus << nl;

                writeTime(file());
                file()
                    << token::TAB << patch.name()
                    << token::TAB << minYplus
                    << token::TAB << maxYplus
                    << token::TAB << avgYplus
                    << endl;
            }
        }
    }

    Log << endl;

    return true;
}
static int ca8210_test_int_write(const uint8_t *buf, size_t len)
{
	int returnvalue, remaining = len;
	int i, attempts = 0;

	pthread_mutex_lock(&tx_mutex);
	do {
		returnvalue = write(DriverFileDescriptor, buf+len-remaining, remaining);
		if (returnvalue > 0)
			remaining -= returnvalue;

		if(returnvalue == -1){
			int error = errno;

			if(errno == EAGAIN){	//If the error is that the device is busy, try again after a short wait
				if(attempts++ < 5){
					struct timespec toSleep;
					toSleep.tv_sec = 0;
					toSleep.tv_nsec = 50*1000000;
					nanosleep(&toSleep, NULL);	//Sleep for ~50ms
					continue;
				}
			}

			pthread_mutex_unlock(&tx_mutex);
			return error;
		}

	} while (remaining > 0);

#ifdef USE_LOGFILE
	pthread_mutex_lock(&file_mutex);
	writeTime(LogFileDescriptor);
	fputs("\r\nWriting data:  ",LogFileDescriptor);
	for(i = 0; i < len; i++){
		fprintf(LogFileDescriptor, " %02x", buf[i]);
	}
	fputs("\r\n",LogFileDescriptor);
	pthread_mutex_unlock(&file_mutex);
#endif

	pthread_mutex_unlock(&tx_mutex);
	return 0;
}
예제 #14
0
void PluginDatabase::updatePersistentMetadataCache()
{
    if (!isPersistentMetadataCacheEnabled() || persistentMetadataCachePath().isEmpty())
        return;

    makeAllDirectories(persistentMetadataCachePath());
    String absoluteCachePath = pathByAppendingComponent(persistentMetadataCachePath(), persistentPluginMetadataCacheFilename);
    deleteFile(absoluteCachePath);

    if (m_plugins.isEmpty())
        return;

    PlatformFileHandle file;
    file = openFile(absoluteCachePath, OpenForWrite);

    if (!isHandleValid(file)) {
        LOG_ERROR("Unable to open plugin metadata cache for saving");
        return;
    }

    char localSchemaVersion = schemaVersion;
    if (writeToFile(file, &localSchemaVersion, 1) != 1) {
        LOG_ERROR("Unable to write plugin metadata cache schema");
        closeFile(file);
        deleteFile(absoluteCachePath);
        return;
    }

    PluginSet::const_iterator end = m_plugins.end();
    for (PluginSet::const_iterator it = m_plugins.begin(); it != end; ++it) {
        if (!(writeUTF8String(file, (*it)->path())
              && writeTime(file, (*it)->lastModified())
              && writeUTF8String(file, (*it)->name())
              && writeUTF8String(file, (*it)->description())
              && writeUTF8String(file, (*it)->fullMIMEDescription()))) {
            LOG_ERROR("Unable to write plugin metadata to cache");
            closeFile(file);
            deleteFile(absoluteCachePath);
            return;
        }
    }

    closeFile(file);
}
예제 #15
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;
}
예제 #16
0
// recursively remove a file branch
gbool GUrlCache::RemoveFiles(const char *directory,time_t olderThan)
{

    CFileFind finder;

    CString dir = directory;

    // add separator
    int l = dir.GetLength();
    if (l == 0) return FALSE;
    if ( !((dir[l-1] == '\\') || (dir[l-1] == '/'))) dir += '\\';

    dir += "*.*";

    CString path;

    CTime creationTime((time_t)0);
    CTime accessTime((time_t)0);
    CTime writeTime((time_t)0);

    // setup the find structure
    BOOL bWorking = finder.FindFile(dir);

    LONGLONG fileSum=0;

    while (bWorking)  { // for all entrys
        if (stop) break;

        bWorking = finder.FindNextFile();

        path = finder.GetFilePath();

        creationTime = (time_t)0;
        accessTime = (time_t)0;
        writeTime = (time_t)0;

        BOOL ret=finder.GetCreationTime(creationTime);
        finder.GetLastAccessTime(accessTime);
        finder.GetLastWriteTime(writeTime);
        time_t t = creationTime.GetTime();

        // if (accessTime.GetTime()>0) t = max(t,accessTime.GetTime());


        if (finder.IsDots( )) {	// ignore . ..

        } else 	if (finder.IsDirectory( )) { // recursively step down
            RemoveFiles(path,olderThan);
            RemoveDirectory(path);
        }
        else {

            DWORD length = finder.GetLength();

            TRACE("F %s c %ld a %ld w %ld size %ld \n",(const char *) path, creationTime.GetTime(),accessTime.GetTime(),writeTime.GetTime(),length);
            if (olderThan >0 ) {

                if (t < olderThan) {
                    if (RemoveFile(path))
                        fileSum += length;
                }


            } else {
                if (RemoveFile(path))
                    fileSum += length;
            }

        }


    }
    finder.Close();

    TRACE("%ld bytes deleted \n",(long) fileSum);

    return TRUE;
}
예제 #17
0
파일: main.c 프로젝트: ryannorton/2048
int main(void) {
    int addScore, position, pauseSel;

    // Initializations
    PLL_Init();  			// Clock set at 80 MHz
    LCD_Init();
    Board_Init();
    Input_Init();
    DAC_Init();
    Random_Init(NVIC_ST_CURRENT_R);
    Timer2_Init(80000000); 	// time interrupt
    Timer1_Init(2000);		// sound interrupt
    EnableInterrupts();
    generateRandomTile();
    drawAllTiles();
    writeScore(0);
    writeHighscore(0);
    writeTime(0);
    displayHighestTile();

    while(1) {

        // draw arrow if ready
        if (arrowReady == 1) {
            // acknowledge flag
            arrowReady = 0;
            // draw arrow
            drawArrow();
        }

        // write time if ready
        if (timeReady == 1) {
            // acknowledge flag
            timeReady = 0;
            // write time
            writeTime(elapsedTime);
        }

        // Play mode and button1 is pushed
        if(Button1 && !pauseMode && !gameOver) {
            // Play sound
            playSound = 1;
            // shift and merge tiles towards arrow
            position = getSliderPosition();
            if (position == 1) {
                shiftLeft();
                addScore = mergeLeft();
                shiftLeft();
            }
            else if (position == 2) {
                shiftUp();
                addScore = mergeUp();
                shiftUp();
            }
            else if (position == 3) {
                shiftRight();
                addScore = mergeRight();
                shiftRight();
            }
            else {
                shiftDown();
                addScore = mergeDown();
                shiftDown();
            }

            eraseBoard();
            drawAllTiles();

            // update score
            score += addScore;
            addScore = 0;
            writeScore(score);
            displayHighestTile();

            // delay before adding new tile
            delay(200);

            // create new tile
            if (countEmptyTiles() != 0) {
                generateRandomTile();
            }
            drawAllTiles();

            // update highest tile image
            displayHighestTile();

            // check if game over
            if (checkGameOver() == 1) {
                gameOver = 1;
            }

            // unset flag
            Button1 = 0;
        }

        // button 2 is pause
        else if (Button2 && !gameOver && !pauseMode) {
            pauseMode = 1;
            pauseSel = 0;

            // disable arrow and timer
            NVIC_ST_CTRL_R = 0;
            TIMER2_CTL_R = 0x00000000;
            LCD_DrawFilledRect(prevX,prevY,20,20,BLACK);

            // draw pause mode screen
            drawPauseMode();

            // acknowledge button
            Button2 = 0;

            // wait until button is pushed
            while (pauseMode) {

                // Button 1 selects current pause selection button
                if (Button1) {

                    // acknowledge button
                    Button1 = 0;
                    Button2 = 0;
                    pauseMode = 0;

                    // if pause selection = "continue" (pauseSel = 0), continue with game
                    if (pauseSel == 0) {

                        // redraw screen
                        eraseBoard();
                        drawAllTiles();

                        // enable gameplay
                        NVIC_ST_CTRL_R = 0x07;
                        TIMER2_CTL_R = 0x00000001;
                    }

                    // if pause selection = "restart" (pauseSel = 0), end game
                    else if (pauseSel == 1) {
                        if (score > highscore) {
                            writeHighscore(score);
                        }
                        score = 0;
                        eraseScore();
                        writeScore(0);
                        clearBoard();
                        eraseBoard();
                        pauseMode = 0;
                        generateRandomTile();
                        drawAllTiles();
                        elapsedTime = 0;
                        eraseTime();
                        writeTime(0);
                        displayHighestTile();
                        NVIC_ST_CTRL_R = 0x07;
                        TIMER2_CTL_R = 0x00000001;
                    }
                }

                // Button 2 changes pause selection
                else if (Button2) {
                    Button2 = 0;
                    if (pauseSel == 0) {
                        pauseSel = 1;
                        LCD_DrawRect(144,112,58,16,BLACK);
                        LCD_DrawRect(222,112,51,16,WHITE);
                    }
                    else if (pauseSel == 1) {
                        pauseSel = 0;
                        LCD_DrawRect(222,112,51,16,BLACK);
                        LCD_DrawRect(144,112,58,16,WHITE);
                    }
                }
            }
        }

        // game over
        if (gameOver == 1) {
            NVIC_ST_CTRL_R = 0;
            TIMER2_CTL_R = 0x00000000;
            LCD_DrawFilledRect(156,38,100,20,BLACK);
            LCD_SetTextColor(255,255,240);
            LCD_Goto(30,5);
            printf("GAME OVER");
            while (Button1 == 0 && Button2 == 0) {}
            Button1 = 0;
            Button2 = 0;
            LCD_DrawFilledRect(prevX,prevY,20,20,BLACK);
            drawGameOver(score, elapsedTime);
            if (score > highscore) {
                writeHighscore(score);
                gameOverHighscore(score);
            }
            // wait til button is pushed
            while (Button1 == 0 && Button2 == 0) {}
            // acknowledge buttons
            Button1 = 0;
            Button2 = 0;
            // start new game
            score = 0;
            eraseScore();
            writeScore(0);
            clearBoard();
            eraseBoard();
            pauseMode = 0;
            generateRandomTile();
            drawAllTiles();
            elapsedTime = 0;
            eraseTime();
            writeTime(0);
            displayHighestTile();
            NVIC_ST_CTRL_R = 0x07;
            TIMER2_CTL_R = 0x00000001;

            // finish game over mode
            gameOver = 0;
        }
    }
}
void TraceEventWriter::processEvent(const trace_event* event) {
	if (event->type == EventType::Complete) {
		if (event->duration < 1000) {
			// Discard events that are less than a millisecond long
			return;
		}
	}

	if (!_first_line) {
		_out << ",";
	}
	_out << "\n{\"tid\": " << event->tid << ",\"ts\":";

	writeTime(_out, event->timestamp);

	_out << ",\"pid\":";
	if (event->pid == GPU_PID) {
		_out << "\"GPU\"";
	}
	else {
		_out << event->pid;
	}

	if (event->scope != nullptr) {
		_out << ",\"cat\":\"" << event->scope->getName() << "\"";
		_out << ",\"id\":\"" << reinterpret_cast<const void*>(event->scope) << "\"";
	}

	_out << ",\"name\":\"" << event->category->getName() << "\",\"ph\":\"" << getTypeStr(event->type) << "\"";

	switch (event->type) {
		case EventType::Complete:
			writeCompleteEvent(_out, event);
			break;
		case EventType::Begin:
		case EventType::End:
			// Nothing to do here
			break;
		case EventType::AsyncBegin:
		case EventType::AsyncStep:
		case EventType::AsyncEnd:
			// Nothing to do here...
			break;
		case EventType::Counter: {
			auto flags = _out.flags();
			_out << std::fixed;

			_out << ",\"args\": {\"value\": " << event->value << "}";

			// and now restore it
			_out.flags(flags);
			break;
		}
		default:
			Assertion(false, "Unhandled enum value! This function should not have been called with this value!");
			break;
	}

	_out << "}";

	_first_line = false;
}
예제 #19
0
gbool GUrlCache::GetCacheStats(const char *directory, time_t &oldest,DWORD &spaceInUse, int &filesInUse)
{

    CFileFind finder;

    CString dir = directory;

    // add separator
    int l = dir.GetLength();
    if (l == 0) return FALSE;
    if ( !((dir[l-1] == '\\') || (dir[l-1] == '/'))) dir += '\\';

    dir += "*.*";

    CString path;

    CTime creationTime((time_t)0);
    CTime accessTime((time_t)0);
    CTime writeTime((time_t)0);

    // setup the find structure
    BOOL bWorking = finder.FindFile(dir);


    while (bWorking)  { // for all entrys
        if (stop) break;

        bWorking = finder.FindNextFile();

        path = finder.GetFilePath();

        creationTime = (time_t)0;
        accessTime = (time_t)0;
        writeTime = (time_t)0;

        BOOL ret=finder.GetCreationTime(creationTime);
        finder.GetLastAccessTime(accessTime);
        finder.GetLastWriteTime(writeTime);
        time_t t = creationTime.GetTime();

        if (accessTime.GetTime()>0) t = max(t,accessTime.GetTime());


        if (finder.IsDots( )) {	// ignore . ..

        } else 	if (finder.IsDirectory( )) { // recursively step down
            GetCacheStats(path,oldest,spaceInUse,filesInUse);
        }
        else {

            DWORD length = finder.GetLength();

            TRACE("F %s c %ld a %ld w %ld size %ld \n",(const char *) path, creationTime.GetTime(),accessTime.GetTime(),writeTime.GetTime(),length);
            oldest = min(oldest,t);
            filesInUse++;
            spaceInUse += length;

        }


    }
    finder.Close();


    return TRUE;
}
예제 #20
0
int
main(int argc, const char ** argv)
{
#ifdef VISP_HAVE_LAPACK_C
  try {
    unsigned int nb_matrices=1000;
    unsigned int nb_iterations=10;
    unsigned int nb_rows = 6;
    unsigned int nb_cols = 6;
    bool verbose = false;
    std::string plotfile("plot.txt");
    bool use_plot_file=false;
    std::ofstream of;

    double t, qr_time, lu_time,pi_time,chol_time;
    // Read the command line options
    if (getOptions(argc, argv, nb_matrices,nb_iterations,use_plot_file,plotfile,nb_rows,nb_cols,verbose) == false) {
      exit (-1);
    }

    if(use_plot_file){
      of.open(plotfile.c_str());
    }

    for(unsigned int iter=0;iter<nb_iterations;iter++){
      std::vector<vpMatrix> benchQR;
      std::vector<vpMatrix> benchLU;
      std::vector<vpMatrix> benchCholesky;
      std::vector<vpMatrix> benchPseudoInverse;
      if(verbose)
        std::cout << "********* generating matrices for iteration " << iter << "." << std::endl;
      for(unsigned int i=0;i<nb_matrices;i++){
        vpMatrix cur;
        double det=0.;
        //don't put singular matrices in the benchmark
        for(cur=makeRandomMatrix(nb_rows,nb_cols);std::abs(det=cur.AtA().det())<.01;cur = makeRandomMatrix(nb_rows,nb_cols))
          if(verbose){
            std::cout << "Generated random matrix A*tA=" << std::endl << cur.AtA() << std::endl;
            std::cout << "generated random matrix not invertibleL: det="<<det<< ". Retrying..." << std::endl;
          }
        benchCholesky.push_back(cur);
        benchQR.push_back(cur);
        benchLU.push_back(cur);
        benchPseudoInverse.push_back(cur);
      }

      if(verbose)
        std::cout << "\t Inverting " << benchCholesky[0].AtA().getRows() << "x" << benchCholesky[0].AtA().getCols() << " matrix using cholesky decomposition." << std::endl;
      t = vpTime::measureTimeMs() ;
      for(unsigned int i=0;i<nb_matrices;i++){
        benchCholesky[i]=benchCholesky[i].AtA().inverseByCholesky()*benchCholesky[i].transpose();
      }
      chol_time = vpTime::measureTimeMs() - t ;

      if(verbose)
        std::cout << "\t Inverting " << benchLU[0].AtA().getRows() << "x" << benchLU[0].AtA().getCols() << " matrix using LU decomposition." << std::endl;
      t = vpTime::measureTimeMs() ;
      for(unsigned int i=0;i<nb_matrices;i++)
        benchLU[i] = benchLU[i].AtA().inverseByLU()*benchLU[i].transpose();
      lu_time = vpTime::measureTimeMs() -t ;

      if(verbose)
        std::cout << "\t Inverting " << benchQR[0].AtA().getRows() << "x" << benchQR[0].AtA().getCols() << " matrix using QR decomposition." << std::endl;
      t = vpTime::measureTimeMs() ;
      for(unsigned int i=0;i<nb_matrices;i++){
        benchQR[i]=benchQR[i].AtA().inverseByQR()*benchQR[i].transpose();
      }
      qr_time = vpTime::measureTimeMs() - t ;

      if(verbose)
        std::cout << "\t Inverting " << benchPseudoInverse[0].AtA().getRows() << "x" << benchPseudoInverse[0].AtA().getCols() << " matrix while computing pseudo-inverse." << std::endl;
      t = vpTime::measureTimeMs() ;
      for(unsigned int i=0;i<nb_matrices;i++){
        benchPseudoInverse[i]=benchPseudoInverse[i].pseudoInverse();
      }
      pi_time = vpTime::measureTimeMs() - t ;

      double avg_err_lu_qr=0.;
      double avg_err_lu_pi=0.;
      double avg_err_lu_chol=0.;
      double avg_err_qr_pi=0.;
      double avg_err_qr_chol=0.;
      double avg_err_pi_chol=0.;

      for(unsigned int i=0;i<nb_matrices;i++){
        avg_err_lu_qr+= (benchQR[i]-benchLU[i]).euclideanNorm();
        avg_err_lu_pi+= (benchPseudoInverse[i]-benchLU[i]).euclideanNorm();
        avg_err_qr_pi+= (benchPseudoInverse[i]-benchQR[i]).euclideanNorm();
        avg_err_qr_chol+= (benchCholesky[i]-benchQR[i]).euclideanNorm();
        avg_err_lu_chol+= (benchCholesky[i]-benchLU[i]).euclideanNorm();
        avg_err_pi_chol+= (benchCholesky[i]-benchPseudoInverse[i]).euclideanNorm();
      }

      avg_err_lu_qr/=nb_matrices;
      avg_err_lu_pi/=nb_matrices;
      avg_err_qr_pi/=nb_matrices;

      if(use_plot_file){
        of << iter << "\t" << lu_time << "\t" << qr_time << "\t" << pi_time << "\t" << chol_time << "\t" << avg_err_lu_qr << "\t" << avg_err_qr_pi << "\t" << avg_err_lu_pi << "\t" << avg_err_qr_chol << "\t" << avg_err_lu_chol << "\t" <<  avg_err_pi_chol << std::endl;
      }
      if(verbose || !use_plot_file){
        writeTime("LU",lu_time);
        writeTime("QR",qr_time);
        writeTime("Pseudo-inverse",pi_time);
        writeTime("Cholesky",chol_time);
      }
    }
    return 0;
  }
  catch(vpException e) {
    std::cout << "Catch an exception: " << e << std::endl;
    return 1;
  }

#else
  (void)argc;
  (void)argv;
  std::cout << "You don't have lapack installed" << std::endl;
  return 0;
#endif
}
예제 #21
0
/**
 * Header and message
 *  @param pTextString		TODO describtion  
 *  @param pType			TODO describtion 
 */
void DebugApi::header(string pTextString, int pType) {
	if (!_ok) return;

	switch (pType) {
		// Ok
	case(1): {
		// Line
		*_count << "          ";
		*_count << " [  OK   ] ";
		advance();
        *_count << pTextString.c_str() << endl;

		break;
	}
	// Error
	case(2): {
		// Line
		*_count << "          ";
		*_count << " [ ERROR ] ";
		advance();
        *_count << pTextString.c_str() << endl;

		// If we are inside a BEGIN / END, we go out
		if (_depth > 0) {
			// Going back
			_depth -= ESP;
			// Close bracket
			*_count << "                     ";
			advance();
			*_count << "}" << endl;

			// Line
			writeTime();
			*_count << " [  END  ] ";
			advance();
			*_count << "Error occurred";

			// Measure the time between BEGIN and END
			double elapsedTime = _timer.getTicks() - _tableTime [(_depth + ESP) / ESP];
			if (elapsedTime < 0) elapsedTime = 0; // Medida de seguridad
			*_count << " [Elaped time = " << elapsedTime * 0.001f << " seg]" << endl;

			// Line jump after BEGIN/END
			if (!_depth) {
				*_count << "---------------------------------------------------------------------" << endl;
			}
		}

		break;

	}
	// Info
	// Info dosen't make a line jump in order DataChar and DataInt could write just after that line
	case(3): {
		// Line
		*_count << "          ";
		*_count << " [ INFO  ] ";
		advance();
        *_count << pTextString.c_str();

		break;
	}
	// Warning
	case(4): {
		// Line
		*_count << "          ";
		*_count << " [WARNING] ";
		advance();
        *_count << pTextString.c_str() << endl;

		break;
	}
	// Begin
	case(5): {
		// Line
		writeTime();
		*_count << " [ BEGIN ] ";
		advance();
        *_count << "-- " << pTextString.c_str() << " --" << endl;

		// Open brackets
		*_count << "                     ";
		advance();
		*_count << "{" << endl;

		// Advance
		_depth += ESP;

		// Store the current time in the time table
		_tableTime [_depth / ESP] = _timer.getTicks();

		break;
	}
	// End
	case(6): {
		// Going back
		_depth -= ESP;
		// Close bracket
		*_count << "                     ";
		advance();
		*_count << "}" << endl;

		// Line
		writeTime();
		*_count << " [  END  ] ";
		advance();
        *_count << pTextString.c_str();

		// Measure the time between BEGIN and END
		double elapsedTime = _timer.getTicks() - _tableTime [(_depth + ESP) / ESP];
		if (elapsedTime < 0) elapsedTime = 0; // Security Measure
		*_count << " [Elapsed time = " << elapsedTime * 0.001f << " seg]" << endl;

		// Line jump after BEGIN/END
		if (!_depth) {
			*_count << "---------------------------------------------------------------------" << endl;
		}

		break;
	}
	}
}
예제 #22
0
/**
 * Controller helper routine.
 *
 * Return the next slave available for processing work.
 */
int ctrlWaitForSlave(bool runningSlavesOnly = false) {
    if ((! runningSlavesOnly) && (nRunningSlaves < nSlaves)) {
        // We can use a slave that hasn't been started yet.
        // It's probably number (nRunningSlaves + 1).
        if (slaveTask[nRunningSlaves + 1].pairing < 0)
            return nRunningSlaves + 1;

        // Sigh.  Better go look.
        for (int slave = 1; slave <= nSlaves; slave++)
            if (slaveTask[slave].pairing < 0)
                return slave;

        // Strange.
        // Shouldn't get here ever.
        std::cerr << "ERROR: Something is seriously wrong." << std::endl;
        std::cerr << "A free slave could not be found." << std::endl;
        controllerError = true;
        return 0;
    }

    // All slaves are currently working.  Wait for the next one to finish.
    long results[3];
    MPI_Status status;
    MPI_Recv(results, 3, MPI_LONG, MPI_ANY_SOURCE, TAG_RESULT, MPI_COMM_WORLD,
        &status);

    int slave = status.MPI_SOURCE;
    time_t totSec = time(0) - slaveTask[slave].start;

    if (results[0] != slaveTask[slave].pairing ||
            results[1] != slaveTask[slave].subtask) {
        ctrlLogStamp() << "ERROR: Mismatched task data for slave "
            << slave << "." << std::endl;
        controllerError = true;
    }

    if (results[2] < 0) {
        ctrlLogStamp() << "ERROR: Unable to run task (see next line)."
            << std::endl;
        controllerError = true;
    }

    ctrlLogStamp() << "Task [" << results[0];
    if (results[1] >= 0)
        logger << '-' << results[1];
    logger << " @ slave " << slave << "]:  ";

    if (results[2] >= 0)
        logger << results[2] << " found";
    else
        logger << "UNABLE TO RUN TASK";

    logger << ", time " << totSec
        << "s (";
    writeTime(logger, totSec);
    logger << ")" << std::endl;

    if (results[2] >= 0)
        totTri += results[2];

    // Tidy up and return our answer.
    slaveTask[slave].pairing = slaveTask[slave].subtask = -1;
    nRunningSlaves--;
    return slave;
}
예제 #23
0
void ConvertXml::write(QTextStream& os)
{
	calcDivisions();
	os << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"
	   << endl;
	os << "<!DOCTYPE score-partwise PUBLIC" << endl;
	os << "    \"-//Recordare//DTD MusicXML 1.0 Partwise//EN\"" << endl;
	os << "    \"http://www.musicxml.org/dtds/partwise.dtd\">" << endl;
	os << endl;
	os << "<score-partwise>\n";
	os << "\t<work>\n";
	os << "\t\t<work-title>" << song->info["TITLE"] << "</work-title>\n";
	os << "\t</work>\n";

// identification
	os << "\n";
	os << "\t<identification>\n";
	os << "\t\t<creator type=\"composer\">" << song->info["ARTIST"] << "</creator>\n";
	os << "\t\t<encoding>\n";
	os << "\t\t\t<encoder>" << song->info["TRANSCRIBER"] << "</encoder>\n";
	os << "\t\t\t<software>KGuitar</software>\n";
	os << "\t\t</encoding>\n";
	os << "\t</identification>\n";

// part list
	os << "\n";
	os << "\t<part-list>\n";
	// loop over all tracks
	for (unsigned int it = 0; it < song->rowCount(); it++) {
		    TabTrack* trk = song->index(it, 0).data(TabSong::TrackPtrRole).value<TabTrack*>();
		os << "\t\t<score-part id=\"P" << it+1 << "\">\n";
		os << "\t\t\t<part-name>" << trk->name << "</part-name>\n";
		// LVIFIX: fill-in real instrument-name instead of "Guitar"
		// note: in DTD 0.6 score-instrument may appear zero or more times
		//       within a score-part
		// note: in DTD 0.7a score-instrument apparently is required
		os << "\t\t\t<score-instrument id=\"P" << it+1
		   << "-I" << it+1 << "\">\n";
		os << "\t\t\t\t<instrument-name>" << "Guitar"
		   << "</instrument-name>\n";
		os << "\t\t\t</score-instrument>\n";
		os << "\t\t\t<midi-instrument id=\"P" << it+1
		   << "-I" << it+1 << "\">\n";
		os << "\t\t\t\t<midi-channel>" << trk->channel
		   << "</midi-channel>\n";
		os << "\t\t\t\t<midi-bank>" << trk->bank
		   << "</midi-bank>\n";
		os << "\t\t\t\t<midi-program>" << trk->patch
		   << "</midi-program>\n";
		os << "\t\t\t</midi-instrument>\n";
		os << "\t\t</score-part>\n";
	} // end for (unsigned int it = 0; ...
	os << "\t</part-list>\n";

// parts
	//TabTrack *trk;
	// loop over all tracks
	for (unsigned int it = 0; it < song->rowCount(); it++) {
		TabTrack* trk = song->index(it, 0).data(TabSong::TrackPtrRole).value<TabTrack*>();
		trk->calcVoices();
		trk->calcStepAltOct();
		trk->calcBeams();
		os << "\n";
		os << "\t<part id=\"P" << it+1 << "\">\n";

		// loop over all bars
		for (uint ib = 0; ib < trk->bars().size(); ib++) {
			os << "\t\t<measure number=\"" << ib + 1 << "\">\n";
			if (ib == 0) {
				// First bar: write all attributes
				os << "\t\t\t<attributes>\n";
				os << "\t\t\t\t<divisions>" << divisions << "</divisions>\n";
				os << "\t\t\t\t<key>\n";
				os << "\t\t\t\t\t<fifths>" << trk->bars()[0].keysig << "</fifths>\n";
				// LVIFX: re-enable when KGuitar supports major/minor modes
				// os << "\t\t\t\t\t<mode>major</mode>\n";
				os << "\t\t\t\t</key>\n";
				writeTime(os, trk->bars()[0].time1, trk->bars()[0].time2);
				os << "\t\t\t\t<staves>2</staves>\n";
				os << "\t\t\t\t<clef number=\"1\">\n";
				os << "\t\t\t\t\t<sign>G</sign>\n";
				os << "\t\t\t\t\t<line>2</line>\n";
				os << "\t\t\t\t\t<clef-octave-change>-1</clef-octave-change>\n";
				os << "\t\t\t\t</clef>\n";
				os << "\t\t\t\t<clef number=\"2\">\n";
				os << "\t\t\t\t\t<sign>TAB</sign>\n";
				os << "\t\t\t\t\t<line>5</line>\n";
				os << "\t\t\t\t</clef>\n";
				writeStaffDetails(os, trk);
				os << "\t\t\t</attributes>\n";
				os << "\t\t\t<sound tempo=\"" << song->tempo << "\"/>\n";
			} else {
				// LVIFIX write time sig if changed
			}

			// loop over all voices in this bar
			for (int i = 0; i < 2; i++) {
				// write only voice 1 in single voice tracks,
				// write all voices in multi voice tracks
				if ((i == 1) || trk->hasMultiVoices()) {
					// loop over all columns in this bar
					for (int x = trk->bars()[ib].start;
							x <= trk->lastColumn(ib); /* nothing */) {
/*
						int tp;
						int dt;
						bool tr;
						if (!trk->getNoteTypeAndDots(x, i, tp, dt, tr)) {
							// LVIFIX: error handling ?
						}
*/
						x += writeCol(os, trk, x, i, true);
					} // end for ((i == 1) || ....
				} // end if (trk->hasMulti ...
			} // end for (int i = 0; ...

			os << "\t\t</measure>\n";
			os << "\n";
		} // end for (uint ib = 0; ...

		os << "\t</part>\n";
	} // end for (unsigned int it = 0; ...
	os << "\n";
	os << "</score-partwise>\n";
}
예제 #24
0
 PWMServo::~PWMServo()
 {
   writeTime(0);
 }
예제 #25
0
TIME OptimisticTickSyncAlgo::GetNextTime(TIME currentTimeParam, TIME nextTime)
{
	TIME nextEstTime;
	TIME myminNextTime;
	TIME currentTime=currentTimeParam;
	//we have processed upto including grated time
	if(nextTime <= grantedTime){
#ifdef PROFILE
		writeTime(currentTimeParam);
#endif
		return nextTime;
	}

	bool canSpeculate=false;
	bool needToRespond=false;
	busywait=false;
	//send all messages
#if DEBUG
	CERR << "Start sync " << currentTime << " " << nextTime << endl;
#endif
	if(currentTime < grantedTime){ //we still have some granted time we need to barier at granted Time
		busywait=true;
		currentTime=grantedTime;
	}
	if(currentTime > this->specFailTime){ //we passed beyond spec. failure time. We can speculatie again.
		this->specFailTime=Infinity;
	}
	do
	{
		canSpeculate=false;
		if(busywait)
			this->timeStepStart(currentTime);
		//we don't need barier
		uint64_t diff=interface->reduceTotalSendReceive();
		//nextEstTime is the granted time the simulator exptects.
		//myminNextTime is the minimum next time the smulator can process.
		//usually for conservative algorithm these two numbers are the same
		//for optimistic however when get knowledge about the the dead time of child process
		//we can use it as the granted time.
		//if I have a packet, I can only
		nextEstTime=currentTimeParam+Integrator::getOneTimeStep();
		myminNextTime=nextEstTime;
		TIME minnetworkdelay=interface->reduceNetworkDelay();
		if(diff==0 && !needToRespond)
		{ //network stable grant next time
#ifdef DEBUG
			CERR << "diff is 0 specFailTime " << specFailTime << endl;
#endif
			myminNextTime=nextEstTime=nextTime;
			if(specFailTime!=Infinity && nextTime < specFailTime){ //we can grant upto spec fail time
#ifdef DEBUG
				CERR << "I'm grating my self " << specFailTime << endl;
#endif
				nextEstTime=specFailTime;
				//since we know the spec will fail until this time, we won't fork!
				canSpeculate=false;
				//we reset specFailTime.
				specFailTime=Infinity;
			}
			else{
				canSpeculate=true;
			}
		}
		else{
			needToRespond=true;
			//diff changed kill the child process if it is still active.
			checkChild(diff);
		}
		minNextTime=nextEstTime;

#ifdef DEBUG
		CERR << "Consensus on message-diff " << diff << endl;
#endif
		TIME specNextTime=0;
		if(diff==0){
			if(!hasChild()){ //we do speculation calculation only if we can speculate
				//we should never attempt to exchange specDiff when Diff > 0, this is an optimization.
				//canSpeculate can be false regardless of Diff==0, in this case
				//we have simulator that needs to respond. So we need to signal others
				//not to speculate at all.
				TIME mySpecNextTime;

				if(canSpeculate && st->worthSpeculation(currentTime,specFailTime)){ //test if it is worht speculating!
					mySpecNextTime=st->getNextSpecTime(currentTime);
				}
				else{
					mySpecNextTime=0;
				}
				//if we don't have a child, we aggregate specNextTime
				//with with minNextTime
				specNextTime=mySpecNextTime;
				interface->aggreateReduceMin(minNextTime,specNextTime);
			}
			else{
				//if we have child we aggregate action
				//with minNextTime
				this->globalAction=comm->action;
				interface->aggreateReduceMin(minNextTime,this->globalAction);
#ifdef DEBUG
				CERR << comm->action << " " << globalAction << endl;
#endif

			}
		} else{ //well, we have message so we use regular reduce min op.
			minNextTime=(TIME)interface->reduceMinTime(nextEstTime);
		}
		//aggregate reduce min operation.

#ifdef DEBUG
		CERR << "Consensus " << minNextTime << " spec: " << specNextTime << " diff:"<< st->getSpecTime() << endl;
		assert(specNextTime==0 || specNextTime > currentTime);
#endif
		//speculation stuff
		TIME specResult=testSpeculationState(specNextTime,currentTime);
		if(specResult > 0) //we are in child! We are granted up to specNextTime
			minNextTime=specNextTime;

		if(minNextTime==0){ //a sim signal endded
#if DEBUG
			CERR << "End Signaled!" << endl;
#endif
			this->finished=true;
			return 0;
		}

		if(minNextTime < myminNextTime){
			//next time is some seconds away and the simulator has to wait so fork speculative unless we already forked
			//update the value of the currentTime
			currentTimeParam = convertToMyTime(Integrator::getCurSimMetric(),minNextTime);
			currentTimeParam = convertToFrameworkTime(Integrator::getCurSimMetric(),currentTimeParam);
			currentTime = minNextTime;
			busywait=true;
		}
		else{
			busywait=false;
		}

		this->grantedTime=minNextTime;

	}while(busywait);

#ifdef PROFILE
	writeTime(currentTimeParam);
#endif

	return myminNextTime;
}
static int ca8210_test_int_exchange(
	const uint8_t *buf,
	size_t len,
	uint8_t *response,
	void *pDeviceRef
)
{
	int Rx_Length, error, i;
	const uint8_t isSynchronous = ((buf[0] & SPI_SYN) && response);

	if(isSynchronous){
		pthread_mutex_lock(&rx_mutex);	//Enforce synchronous write then read
		while(unhandled_sync_count != 0) {pthread_cond_wait(&unhandled_sync_cond, &rx_mutex);}
	}
	else if(buf[0] & SPI_SYN){
		pthread_mutex_lock(&rx_mutex);
		unhandled_sync_count++;
		pthread_mutex_unlock(&rx_mutex);
	}

	error = ca8210_test_int_write(buf, len);
	if(error){
		//Revert all state changes and release mutexes
		if(isSynchronous)pthread_mutex_unlock(&rx_mutex);
		else if(buf[0] & SPI_SYN){
			pthread_mutex_lock(&rx_mutex);
			unhandled_sync_count--;
			pthread_mutex_unlock(&rx_mutex);
		}

		//Call the errorcallback or crash the program
		if(errorcallback) errorcallback(error);
		else abort();

		//Return a failure to the next highest layer
		return -1;
	}

	if (isSynchronous) {
		do {
			Rx_Length = read(DriverFileDescriptor, response, (size_t) 0);
			
#ifdef USE_LOGFILE
			if (Rx_Length > 0) {
				pthread_mutex_lock(&file_mutex);
				writeTime(LogFileDescriptor);
				fputs("\r\nReceived  Sync:",LogFileDescriptor);
				for(i = 0; i < Rx_Length; i++){
					fprintf(LogFileDescriptor, " %02x", response[i]);
				}
				fputs("\r\n",LogFileDescriptor);
				pthread_mutex_unlock(&file_mutex);
			}
#endif

			if(Rx_Length > 0 && !(response[0] & SPI_SYN)){
				//Unexpected asynchronous response
				add_to_queue(response, Rx_Length);
				Rx_Length = 0;
			}

		} while (Rx_Length == 0);
		pthread_mutex_unlock(&rx_mutex);
	}


	return 0;
}
예제 #27
0
int main(int argc, char** argv)
{
	int 		my_rank,
				procs;

	MPI_Status	status;

	mpz_t 		q,
				p,
				pq,
				n,
				gap,
				sqn;

	mpz_t			*k;

	double 		*timearray;
	double		begin, end;
	double 		time_spent;
	
	int 		done = 0,
				found = 0;

	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
	MPI_Comm_size(MPI_COMM_WORLD, &procs);


	begin = MPI_Wtime();

	mpz_init(n);
	mpz_init(q);
	mpz_init(p);
	mpz_init(pq);
	mpz_init(sqn);
	mpz_init(gap);

	mpz_set_str(n,argv[1],10);
	mpz_sqrt(sqn,n);
	mpz_set(gap, sqn);

	mpz_set_ui(p,1);
	mpz_nextprime(q, p);


	size_t mag = mpz_sizeinbase (gap, 10);
	mag=mag*procs;

	k = (mpz_t*)malloc(sizeof(mpz_t)*(mag+1));
	
	mpz_t temp;
	mpz_init(temp);
	mpz_tdiv_q_ui(temp,gap,mag);	

	for (int i=0;i<=mag;i++)
	{
		mpz_init(k[i]);
		mpz_mul_ui(k[i],temp,i);
	}
	mpz_set(k[mag],sqn);





	int counter=0;


	for (int i=my_rank; i<mag; i=i+procs)
	{
		mpz_set(q,k[i]);

		mpz_sub_ui(q,q,1);
		mpz_nextprime(q,q);


		while (( mpz_cmp(q,k[i+1]) <= 0 )&&(!done)&&(!found)&&(mpz_cmp(q,sqn)<=0))
		{//finding the prime numbers
			counter++;
			if (counter%5000==0)MPI_Allreduce(&found, &done, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);

			if (mpz_divisible_p(n,q)==0) 
			{//if n is not divisible by q
				mpz_nextprime(q,q);
				continue;
			}

			//since it is divisible, try n/q and see if result is prime
			mpz_divexact(p,n,q);
			int reps;
			if (mpz_probab_prime_p(p,reps)!=0)
			{
				found = 1;
				done = 1;
			}
			else
			{
				mpz_nextprime(q,q);
			}
		}//done finding primes

		
		if (found || done) break;
		
	}
	
	end = MPI_Wtime();



	if (found)
	{
		MPI_Allreduce(&found, &done, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
		gmp_printf("*************************\nP%d: Finished\np*q=n\np=%Zd q=%Zd n=%Zd\n*************************\n", my_rank,p,q,n);
	}
	else if (!done)
	{
		while (!done&&!found)
			MPI_Allreduce(&found, &done, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
	}



	time_spent = (double)(end - begin);





	if (my_rank!=0)
	{
		MPI_Send(&time_spent, sizeof(double),MPI_CHAR,0,0,MPI_COMM_WORLD);
	}
	else
	{
		timearray = (double*)malloc(sizeof(double)*procs);
		
		
		timearray[0] = time_spent;

		int j; 
		for (j = 1; j<procs;j++)
		{
			double *ptr = timearray+j;
			MPI_Recv(ptr, sizeof(double),MPI_CHAR,j,0,MPI_COMM_WORLD,&status);
		}


		writeTime(argv[1],timearray,procs);
		free(timearray);

	}


	
	free(k);

	MPI_Finalize();
	return 0;
}
예제 #28
0
// add files to list
gbool GFileSorter::AddFiles(const char *directory,time_t &maxFileTime,BOOL &stop)
{

    CFileFind finder;

    CString dir = directory;

    // add separator
    int l = dir.GetLength();
    if (l == 0) return FALSE;
    if ( !((dir[l-1] == '\\') || (dir[l-1] == '/'))) dir += '\\';

    dir += "*.*";

    CString path;

    CTime creationTime((time_t)0);
    CTime accessTime((time_t)0);
    CTime writeTime((time_t)0);

    // setup the find structure
    BOOL bWorking = finder.FindFile(dir);


    while (bWorking)  { // for all entrys
        if (stop) break;

        bWorking = finder.FindNextFile();

        path = finder.GetFilePath();

        creationTime = (time_t)0;
        accessTime = (time_t)0;
        writeTime = (time_t)0;

        BOOL ret=finder.GetCreationTime(creationTime);
        finder.GetLastAccessTime(accessTime);
        finder.GetLastWriteTime(writeTime);

        time_t t = creationTime.GetTime();

        if (writeTime.GetTime()>0) t = max(t,writeTime.GetTime()); // HG wg Kristof

        if (accessTime.GetTime()>0) t = max(t,accessTime.GetTime());

        if (finder.IsDots( )) {	// ignore . ..

        } else 	if (finder.IsDirectory( )) { // recursively step down

            t=0; // we want to delete empty directories new 20.10.98
            AddFiles(path,t,stop);

            DWORD length = 0;

            // to do get date of latest
            TRACE("D %s c %ld a %ld w %ld size %ld \n",(const char *) path, creationTime.GetTime(),accessTime.GetTime(),writeTime.GetTime(),length);

            // time is the max of the child time +1
            GFSortEntry *e = new GFSortEntry(path,t+1,length,gtrue);

            if (!e) break;
            if (!Add(e)) break;

            if (t>maxFileTime) maxFileTime = t;


        }
        else {

            DWORD length = finder.GetLength(); // get length 64
            fileSum += length;

            TRACE("F %s c %ld a %ld w %ld size %ld \n",(const char *) path, creationTime.GetTime(),accessTime.GetTime(),writeTime.GetTime(),length);
            GFSortEntry *e = new GFSortEntry(path,t,length);

            if (t>maxFileTime) maxFileTime = t;

            if (!e) break;
            if (!Add(e)) break;
        }


    }
    finder.Close();

    //TRACE("%ld bytes \n",(long)fileSum);

    return TRUE;
}