コード例 #1
0
ファイル: ResourceManager.cpp プロジェクト: dreamsxin/rippled
 ManagerImp (beast::insight::Collector::ptr const& collector,
     beast::Journal journal)
     : journal_ (journal)
     , logic_ (collector, stopwatch(), journal)
 {
     thread_ = std::thread {&ManagerImp::run, this};
 }
コード例 #2
0
ファイル: mud.cpp プロジェクト: carriercomm/RadMud
bool Mud::startMud()
{
    // Create a stopwatch for general timing information.
    Stopwatch<std::chrono::milliseconds> stopwatch("Boot");
    Logger::log(LogLevel::Global, "#--------------------------------------------#");
    Logger::log(LogLevel::Global, "             XXXXXXXXXXXXX                ");
    Logger::log(LogLevel::Global, "  /'--_###XXXXXXXXXXXXXXXXXXX###_--'\\    ");
    Logger::log(LogLevel::Global, "  \\##/#/#XXXXXXXXXXXXXXXXXXXXX#\\#\\##/  ");
    Logger::log(LogLevel::Global, "   \\/#/#XXXXXXXXXXXXXXXXXXXXXXX#\\#\\/   ");
    Logger::log(LogLevel::Global, "    \\/##XXXXXXXXXXXXXXXXXXXXXXX##\\/     ");
    Logger::log(LogLevel::Global, "     ###XXXX  ''-.XXX.-''  XXXX###        ");
    Logger::log(LogLevel::Global, "       \\XXXX               XXXX/         ");
    Logger::log(LogLevel::Global, "         XXXXXXXXXXXXXXXXXXXXX            ");
    Logger::log(LogLevel::Global, "         XXXX XXXX X XXXX XXXX            ");
    Logger::log(LogLevel::Global, "         XXX # XXX X XXX # XXX            ");
    Logger::log(LogLevel::Global, "        /XXXX XXX XXX XXX XXXX\\          ");
    Logger::log(LogLevel::Global, "       ##XXXXXXX X   X XXXXXXX##          ");
    Logger::log(LogLevel::Global, "      ##   XOXXX X   X XXXOX   ##         ");
    Logger::log(LogLevel::Global, "      ##    #XXXX XXX XXX #    ##         ");
    Logger::log(LogLevel::Global, "       ##..##  XXXXXXXXX  ##..##          ");
    Logger::log(LogLevel::Global, "        ###      XXXXX     ####           ");
    Logger::log(LogLevel::Global, "#--------------------------------------------#");
    Logger::log(LogLevel::Global, "|                   RadMud                   |");
    Logger::log(LogLevel::Global, "| Created by : Enrico Fraccaroli.            |");
    Logger::log(LogLevel::Global, "| Date       : 29 September 2014             |");
    Logger::log(LogLevel::Global, "#--------------------------------------------#");
    Logger::log(LogLevel::Global, "Booting...");
    Logger::log(LogLevel::Global, "Initializing Mud Variables...");
    if (!this->initVariables())
    {
        Logger::log(LogLevel::Error, "Something gone wrong during variables initialization.");
        return false;
    }

    Logger::log(LogLevel::Global, "Initializing Commands...");
    LoadCommands();

    Logger::log(LogLevel::Global, "Initializing States...");
    LoadStates();

    Logger::log(LogLevel::Global, "Initializing MSDP States...");
    LoadProtocolStates();

    Logger::log(LogLevel::Global, "Initializing Database...");
    if (!this->initDatabase())
    {
        Logger::log(LogLevel::Error, "Something gone wrong during database initialization.");
        return false;
    }

    Logger::log(LogLevel::Global, "Initializing Communications...");
    if (!this->initComunications())
    {
        Logger::log(LogLevel::Error, "Something gone wrong during initialization of comunication.");
        return false;
    }

    Logger::log(LogLevel::Global, "Booting Done (" + ToString(stopwatch.elapsed()) + ").");
    return true;
}
コード例 #3
0
ファイル: simulator_driver.c プロジェクト: T-R0D/Past-Courses
/*==============================================================================
    DRIVER PROGRAM
==============================================================================*/
int main( int argc, char** argv )
{
    // start the timer to track the system bootup time
    stopwatch( 's', GLOBAL_CLOCK );

    // variables
    int system_status = NO_ERRORS;
    ConfigData configurations;
    Heap ready_queue;
    DeviceSet device_set;
    ActivityLog activity_log;

    // perform system bootup actions (which does actually include the
    // inittialization of the above the items)
    system_status = bootSystem( &configurations, &ready_queue, &activity_log );

    // case: the system booted successfully
    if( system_status = NO_ERRORS )
    {
        // execute the simulation
        system_status = executeSimulation( &configurations, &ready_queue,
                                           &device_set, &activity_log );
    }

    // dump the activity log to the specified locations
    dumpActivityData( &configurations, &activity_log );

    // return the program run status to end the program
    return system_status;
}
コード例 #4
0
void SampleGeneratorJob::execute(const size_t thread_index)
{
#ifdef PRINT_DETAILED_PROGRESS
    Stopwatch<DefaultWallclockTimer> stopwatch(0);
    stopwatch.measure();
    const double t1 = stopwatch.get_seconds();
#endif

    // We will base the number of samples to be rendered by this job on
    // the number of samples already reserved (not necessarily rendered).
    const uint64 current_sample_count = m_sample_counter.read();

    // Reserve a number of samples to be rendered by this job.
    const uint64 acquired_sample_count =
        m_sample_counter.reserve(
            samples_to_samples_per_job(current_sample_count));

    // Terminate this job is there are no more samples to render.
    if (acquired_sample_count == 0)
        return;

    // The first phase is uninterruptible in order to always have something to
    // show during navigation. todo: the renderer freezes if it cannot generate
    // samples during this phase; fix.
    const bool abortable = current_sample_count > SamplesInUninterruptiblePhase;

    // Render the samples and store them into the accumulation buffer.
    if (abortable)
    {
        m_sample_generator->generate_samples(
            static_cast<size_t>(acquired_sample_count),
            m_buffer,
            m_abort_switch);
    }
    else
    {
        AbortSwitch no_abort;
        m_sample_generator->generate_samples(
            static_cast<size_t>(acquired_sample_count),
            m_buffer,
            no_abort);
    }

#ifdef PRINT_DETAILED_PROGRESS
    stopwatch.measure();
    const double t2 = stopwatch.get_seconds();

    RENDERER_LOG_DEBUG(
        "job " FMT_SIZE_T ", rendered " FMT_UINT64 " samples%s, in %s",
        m_job_index,
        acquired_sample_count,
        abortable ? "" : " (non-abortable)",
        pretty_time(t2 - t1).c_str());
#endif

    // Reschedule this job.
    if (!abortable || !m_abort_switch.is_aborted())
        m_job_queue.schedule(this, false);
}
コード例 #5
0
ファイル: simulator_driver.c プロジェクト: T-R0D/Past-Courses
/*==============================================================================
    FUNCTION IMPLEMENTATIONS
==============================================================================*/
int bootSystem( ConfigData* configurations, Heap* ready_queue,
                ActivityLog* activity_log )
{
    // read the configuration data
    readConfigurationData( configurations, "test.txt" );

    // read in the meta data and load the main scheduler

    // store the time for starting up the system in the activity log
    logEvent( activity_log, SYSTEM, "System booted",
               stopwatch( 'x', GLOBAL_CLOCK ) );
}
コード例 #6
0
ファイル: bn_testFunc.c プロジェクト: ENAC-Robotique/Robots
/* Deamon managing the sending of all the messages.
 * Must run on the source
 */
int cbr_deamon(){
    sFluxDescriptor *curP;
    int retval;

    //prepare the test packet
    sMsg testPkt;
    testPkt.header.type=E_TEST_PKT;

    //for every entry
    for ( curP=fluxDB ; curP!=0 ; curP=curP->next){

        //check amount of messages left
        if ( curP!=0 ){

            //check stopwatch
            if ( stopwatch(&(curP->sw)) >= curP->period ){

                //restart it
                curP->sw=0;
                stopwatch(&(curP->sw));

                //fill the pkt with this flux data
                testPkt.header.destAddr=curP->receiver;
                testPkt.header.size=curP->size;
                testPkt.payload.testMsg.fluxID=curP->fluxID;

                //send message according to ack field
                if ( curP->ack ) retval=bn_sendAck(&testPkt);
                else retval=bn_send(&testPkt);

                //log result
                if ( retval<0 ) curP->numberNSend++;
                else curP->numberSend++;

                curP->numberLeft--;
            }
        }
    }
    return 0;
}
コード例 #7
0
ファイル: bn_testFunc.c プロジェクト: ENAC-Robotique/Robots
int well_recordPkt(sMsg *msg){
    sStatDescriptor *curP=0, *prevP=statDB;

    //record global stat

    //search for the duet (sender,fluxID) in the DB and update its value
    for (curP=statDB; curP!=0 && (msg->header.srcAddr==curP->sender && msg->payload.testMsg.fluxID==curP->fluxID) ; curP=curP->next){
        prevP=curP;
    }
    //if found, update stat values
    if ( curP!=0 ) {
        //increment number of pkts
        curP->numberRX++;

        //compute  man store mean IAT
        curP->meanIAT=( stopwatch(&(curP->sw))*(curP->numberRX - 1) + curP->meanIAT)/curP->numberRX;

        //restart stopwatch
        curP->sw=0;
        stopwatch(&(curP->sw));
    }
    //if not found, create new entry
    else {

        //allocate memory
        if ( (curP=malloc(sizeof(sStatDescriptor)))<0) return -ERR_INSUFFICIENT_MEMORY;
        prevP->next=curP;

        //fill it
        curP->fluxID=msg->payload.testMsg.fluxID;
        curP->meanIAT=0;
        curP->next=0;
        curP->numberRX=1;
        curP->sender=msg->header.srcAddr;
        curP->sw=0;
        stopwatch(&(curP->sw));
    }
    return 0;
}
コード例 #8
0
ファイル: shader.cpp プロジェクト: PaulZed/mapbox-gl-native
Shader::Shader(const char* name_, const char* vertexSource, const char* fragmentSource, gl::ObjectStore& store, Defines defines)
    : name(name_)
    , program(store.createProgram())
    , vertexShader(store.createShader(GL_VERTEX_SHADER))
    , fragmentShader(store.createShader(GL_FRAGMENT_SHADER))
{
    util::stopwatch stopwatch("shader compilation", Event::Shader);

    if (!compileShader(vertexShader, vertexSource)) {
        Log::Error(Event::Shader, "Vertex shader %s failed to compile: %s", name, vertexSource);
        throw util::ShaderException(std::string { "Vertex shader " } + name + " failed to compile");
    }

    std::string fragment(fragmentSource);
    if (defines & Defines::Overdraw) {
        assert(fragment.find("#ifdef OVERDRAW_INSPECTOR") != std::string::npos);
        fragment.replace(fragment.find_first_of('\n'), 1, "\n#define OVERDRAW_INSPECTOR\n");
    }

    if (!compileShader(fragmentShader, fragment.c_str())) {
        Log::Error(Event::Shader, "Fragment shader %s failed to compile: %s", name, fragmentSource);
        throw util::ShaderException(std::string { "Fragment shader " } + name + " failed to compile");
    }

    // Attach shaders
    MBGL_CHECK_ERROR(glAttachShader(program.get(), vertexShader.get()));
    MBGL_CHECK_ERROR(glAttachShader(program.get(), fragmentShader.get()));

    // Bind attribute variables
    MBGL_CHECK_ERROR(glBindAttribLocation(program.get(), a_pos, "a_pos"));
    MBGL_CHECK_ERROR(glBindAttribLocation(program.get(), a_extrude, "a_extrude"));
    MBGL_CHECK_ERROR(glBindAttribLocation(program.get(), a_offset, "a_offset"));
    MBGL_CHECK_ERROR(glBindAttribLocation(program.get(), a_data, "a_data"));
    MBGL_CHECK_ERROR(glBindAttribLocation(program.get(), a_texture_pos, "a_texture_pos"));

    // Link program
    GLint status;
     MBGL_CHECK_ERROR(glLinkProgram(program.get()));

    MBGL_CHECK_ERROR(glGetProgramiv(program.get(), GL_LINK_STATUS, &status));
    if (status == 0) {
        GLint logLength;
        MBGL_CHECK_ERROR(glGetProgramiv(program.get(), GL_INFO_LOG_LENGTH, &logLength));
        const auto log = std::make_unique<GLchar[]>(logLength);
        if (logLength > 0) {
            MBGL_CHECK_ERROR(glGetProgramInfoLog(program.get(), logLength, &logLength, log.get()));
            Log::Error(Event::Shader, "Program failed to link: %s", log.get());
        }
        throw util::ShaderException(std::string { "Program " } + name + " failed to link: " + log.get());
    }
}
コード例 #9
0
ファイル: main.c プロジェクト: intrinseca/eaa
void randomAccessTest(int reps, int verbose)
{
    int i;

    struct timedReadParams params;

    int start;
    double timeTaken;

    int starts[RANDOM_ACCESS_MAX_REPS];
    double times[RANDOM_ACCESS_MAX_REPS];

    spinUp();

    g_print("Beginning test (%d repetitions)\n", reps);

    for(i = 0; i < reps; i++)
    {
        start = g_random_int_range(0, CDROM_NUM_SECTORS - RANDOM_ACCESS_READ_LENGTH);

        params.sector = start;
        params.count = RANDOM_ACCESS_READ_LENGTH;

        timeTaken = stopwatch(timedRead, &params);

        if(verbose)
        {
            g_print("\ttest %d:\n", i + 1);
            g_print("\t\tstart: %d\n", start);
            g_print("\t\ttime: %f\n", timeTaken);
        }
        else
        {
            g_print(".");
        }

        starts[i] = start;
        times[i] = timeTaken;
    }

    if(!verbose)
    {
        g_print("\n");
    }

    for( i = 0; i < reps; i++)
    {
        fprintf(output, "%d,%f\n", starts[i], times[i]);
    }
}
コード例 #10
0
ファイル: hello.c プロジェクト: zzy1993/mission_impossible
int main(int argc, char **argv)
{
	int counter=0;
	while(1)
	{
		stopwatch();
		//printf(1, "process %d elapses 1 second\n", (int)getpid());
		counter++;
		printf(1, "process %d counter value is %d\n", (int)getpid(), counter);

		if(counter==100)
			break;
	}

	exit();
}
コード例 #11
0
TestRunner::TestRunner(Testables testables, const string& A, const string& B,
        const size_t k, const bool compareResults):
        A(A),
        B(B),
        k(k)
    {

    Testables::iterator it;

    unsigned char currentHash[SHA_DIGEST_LENGTH];
    unsigned char lastHash[SHA_DIGEST_LENGTH];
    bool firstRun = true;
    bool failed = false;

    for(it=testables.begin(); it!=testables.end(); ++it){
	try{
        StopwatchNoBoost stopwatch((*it)->getName(), B.size() * A.size());
        (*it)->run(A, B, k);
        stopwatch.stop();

        if( compareResults ){
            getHash((*it), currentHash);
            if(firstRun == false){
                if( 0 != memcmp(&currentHash[0], &lastHash[0], SHA_DIGEST_LENGTH)){
                std::cerr << "FAILED\n";
                failed = true;
                }
            }

            std::copy(&currentHash[0], &currentHash[SHA_DIGEST_LENGTH], &lastHash[0]);
            firstRun = false;
        }

	}catch(std::bad_alloc& e){
	    cerr << (*it)->getName() << " failed. Reason: " << e.what() << "\n";
    }
	delete (*it);
    }
    if(compareResults){
       if(!failed){
        std::cout << "Success!\n";
        }else{
        std::cerr << "SOME TESTS FAILED!\n";
        }
    }
}
コード例 #12
0
int main_biasedData()
{
	splayset<uint64_t> st;
	Concurrency::concurrent_unordered_set<uint64_t> cs;

	std::thread thread[concurrency_];
	std::vector<std::string> result;

	bpp::Stopwatch stopwatch(true);

	for (size_t tid = 0; tid < concurrency_; ++tid)
		thread[tid] = std::thread([tid, &st, &cs]()
	{
		for (size_t i = tid * item_count; i < (tid+1) * item_count; ++i) {
			st.insert(i);
			cs.insert(i);
		}
	});

	for (size_t tid = 0; tid < concurrency_; ++tid)
		thread[tid].join();
	
	stopwatch.stop();
	std::cout << stopwatch.getMiliseconds() << std::endl;
	std::cout << "Tree size:" << st.size() << std::endl;

	stopwatch.start();

	for (size_t tid = 0; tid < concurrency_; ++tid)
		thread[tid] = std::thread([&st, &cs]()
	{
		for (size_t grp = 0; grp < group_count; ++grp)
			test_group_biased(0, st);
	});

	for (size_t tid = 0; tid < concurrency_; ++tid)
		thread[tid].join();			

	stopwatch.stop();
	std::cout << stopwatch.getMiliseconds() << std::endl;
	std::cout << "Tree size:" << st.size() << std::endl;

	testCSnSt(cs, st);

	return 0;
}
コード例 #13
0
ファイル: main.c プロジェクト: intrinseca/eaa
void speedTest()
{
    int i;

    struct timedReadParams params;

    for(i = 1; i <= 52; i *= 2)
    {
        g_print("Spinning up Drive to %dx...\n", i);
        cdrom_set_speed(&cd, i);
        cdrom_read(&cd, 0, 1000);
        cdrom_clear_cache(&cd);

        params.sector = 0;
        params.count = 1000;

        g_print("\ttime: %f\n", stopwatch(timedRead, &params));
    }
}
コード例 #14
0
ファイル: jade.controller.hpp プロジェクト: jade-cheng/ohana
        ///
        /// Logs information about the specified context for one iteration of
        /// the Nelder-Mead algorithm.
        ///
        void log_iteration(
                const log_args_type & log_args) ///< The Nelder-Mead arguments.
        {
            const auto lle = -log_args.simplex->get_objval();

            const auto dlle = log_args.iteration == 1
                ? value_type(0)
                : lle - _lle;

            std::ostringstream line;
            line << log_args.iteration
                 << std::fixed << std::setprecision(6)
                 << '\t' << _iteration_time;
            matrix_type::set_high_precision(line);
            line << '\t' << dlle << '\t' << lle;
            std::cout << line.str() << std::endl;

            _lle = lle;
            _iteration_time = stopwatch();
        }
コード例 #15
0
ファイル: sdcg.c プロジェクト: berkus/lang-e
int main(int argc, char *argv[]) { 
	int i,j,trials=1, verbose=0,n = 3;
	data_t **a,**b,mask=1023,c = 7;
	v_vptr scale_ptr;

    	/* get options */
    	for (i=1; i<argc; i++)
      		if (strcmp(argv[i],"-n") == 0) n = atoi(argv[++i]);
      		else if (strcmp(argv[i],"-t") == 0) trials = atoi(argv[++i]);
      		else if (strcmp(argv[i],"-m") == 0) mask = atoi(argv[++i]);
      		else if (strcmp(argv[i],"-c") == 0) c = atoi(argv[++i]);
      		else if (strcmp(argv[i],"-v") == 0) verbose = 1;
      		else if (strcmp(argv[i],"-d") == 0) disass = 1;
      		else if (strcmp(argv[i],"-p") == 0) pixie = 1;
      		else if (strcmp(argv[i],"-s") == 0) strength_reduce = 0;

	/* allocate and initialize */
	a = new_matrix(n,n);
	b = new_matrix(n,n);
    	for(i=0;i<n;i++) {
      		for(j=0;j<n;j++) {
                	b[i][j] = (random() & mask) + 1;
		}
	}
	if(verbose) {
		printf("constant = %u\n",c);
		m_print("B", b, n);
	}

	scale_ptr = scale(n, a, b);
        if(verbose) printf("doing constants 1 to %d\n",c);
        for(i=0;i<trials;i++) {
                int c1;
                if(!verbose) startwatch(0);
		for(c1 = 0; c1 < c; c1++)
                        scale_ptr(a, b, c1);
                if(!verbose) stopwatch(0);
        }
	if(verbose) m_print("A", a, n);
	return 0;
}
コード例 #16
0
ファイル: mud.cpp プロジェクト: carriercomm/RadMud
bool Mud::stopMud()
{
    Stopwatch<std::chrono::milliseconds> stopwatch("Shutdown");

    Logger::log(LogLevel::Global, "Shutting down RadMud...");
    Logger::log(LogLevel::Global, "Closing Communications...");
    if (!Mud::instance().closeComunications())
    {
        Logger::log(LogLevel::Error, "The communication has not been closed correctly.");
    }

    Logger::log(LogLevel::Global, "Saving Mud Information...");
    if (!Mud::instance().saveMud())
    {
        Logger::log(LogLevel::Error, "Somwthing has gone wrong during data saving.");
    }

    Logger::log(LogLevel::Global, "Closing Database...");
    if (!SQLiteDbms::instance().closeDatabase())
    {
        Logger::log(LogLevel::Error, "The database has not been closed correctly.");
    }
    Logger::log(LogLevel::Global, "Shutdown Completed (" + ToString(stopwatch.elapsed()) + ").");

    ///////////////////////////////////////////////////////////////////////////
    size_t bIn = MudUpdater::instance().getBandIn();
    size_t bOut = MudUpdater::instance().getBandOut();
    size_t bUnc = MudUpdater::instance().getBandUncompressed();

    // Print some statistics.
    Logger::log(LogLevel::Info, "");
    Logger::log(LogLevel::Info, "Statistics");
    Logger::log(LogLevel::Info, "    In            = " + ToString(bIn) + " Bytes.");
    Logger::log(LogLevel::Info, "    Output        = " + ToString(bOut) + " Bytes.");
    Logger::log(LogLevel::Info, "    Uncompressed  = " + ToString(bUnc) + " Bytes.");
    Logger::log(LogLevel::Info, "    Band. Saved   = " + ToString(bUnc - bOut) + " Bytes.");
    Logger::log(LogLevel::Info, "");
    return true;
}
コード例 #17
0
ファイル: main.c プロジェクト: intrinseca/eaa
void seekTest()
{
    int i;
    struct timedReadParams params;

    double timeTaken;

    int starts[CDROM_NUM_SECTORS / SEEK_RES];
    double times[CDROM_NUM_SECTORS / SEEK_RES];

    cdrom_set_speed(&cd, 0);
    spinUp();

    g_print("Beginning Test...\n");

    for(i = 1; i < CDROM_NUM_SECTORS / SEEK_RES; i ++)
    {
        params.sector = i * SEEK_RES;
        params.count = 10;

        cdrom_clear_cache(&cd);
        cdrom_seek(&cd, 0);

        timeTaken = stopwatch(timedRead, &params);

        g_print(".");

        starts[i] = i * SEEK_RES;
        times[i] = timeTaken;
    }

    g_print("\n");

    for( i = 0; i < CDROM_NUM_SECTORS / SEEK_RES; i++)
    {
        fprintf(output, "%d,%f\n", starts[i], times[i]);
    }
}
コード例 #18
0
TransactionMaster::TransactionMaster (Application& app)
    : mApp (app)
    , mCache ("TransactionCache", 65536, 1800, stopwatch(),
        mApp.journal("TaggedCache"))
{
}
コード例 #19
0
ファイル: uvimager.cpp プロジェクト: jjdmol/LOFAR
/**
 * Add several frequency channels to the uv plane for several combinations
 * of antenna pairs.
 */
void UVImager::Image(const IntegerDomain &frequencies, const IntegerDomain &antenna1Domain, const IntegerDomain &antenna2Domain)
{
	_scanCount = _measurementSet->MaxScanIndex()+1;
	std::cout << "Requesting " << frequencies.ValueCount() << " x " << antenna1Domain.ValueCount() << " x " << antenna2Domain.ValueCount() << " x "
		<< _scanCount << " x " << sizeof(SingleFrequencySingleBaselineData) << " = "
		<< (frequencies.ValueCount() * antenna1Domain.ValueCount() * antenna2Domain.ValueCount() * _scanCount * sizeof(SingleFrequencySingleBaselineData) / (1024*1024))
		<< "MB of memory..." << std::endl;
	SingleFrequencySingleBaselineData ****data =
		new SingleFrequencySingleBaselineData***[frequencies.ValueCount()];
	for(unsigned f = 0;f<frequencies.ValueCount();++f) {
		data[f] =	new SingleFrequencySingleBaselineData**[antenna1Domain.ValueCount()];
		for(unsigned a1 = 0;a1<antenna1Domain.ValueCount();++a1) {
			data[f][a1] = new SingleFrequencySingleBaselineData*[antenna2Domain.ValueCount()];
			for(unsigned a2 = 0;a2<antenna2Domain.ValueCount();++a2) {
				data[f][a1][a2] = new SingleFrequencySingleBaselineData[_scanCount];
				for(unsigned scan = 0; scan<_scanCount;++scan) {
					data[f][a1][a2][scan].flag = true;
					data[f][a1][a2][scan].available = false;
				}
			}	
		}
	}

	std::cout << "Reading all data for " << frequencies.ValueCount() << " frequencies..." << std::flush;
	Stopwatch stopwatch(true);
	MSIterator iterator(*_measurementSet);
	size_t rows = iterator.TotalRows();
	for(unsigned i=0;i<rows;++i,++iterator) {
		unsigned a1 = iterator.Antenna1();
		unsigned a2 = iterator.Antenna2();
		if(antenna1Domain.IsIn(a1) && antenna2Domain.IsIn(a2)) {
			unsigned scan = iterator.ScanNumber();
			unsigned index1 = antenna1Domain.Index(a1);
			unsigned index2 = antenna1Domain.Index(a2);
			int field = iterator.Field();
			double time = iterator.Time();
			casa::Array<casa::Complex>::const_iterator cdI = iterator.CorrectedDataIterator();
			casa::Array<bool>::const_iterator fI = iterator.FlagIterator();
			for(int f=0;f<frequencies.GetValue(0);++f) { ++fI; ++fI; ++fI; ++fI; ++cdI; ++cdI; ++cdI; ++cdI; }
			for(unsigned f=0;f<frequencies.ValueCount();++f) {
				SingleFrequencySingleBaselineData &curData = data[f][index1][index2][scan];
				casa::Complex xxData = *cdI;
				++cdI; ++cdI; ++cdI;
				casa::Complex yyData = *cdI;
				++cdI;
				curData.data = xxData + yyData;
				bool flagging = *fI;
				++fI; ++fI; ++fI;
				flagging = flagging || *fI;
				++fI;
				curData.flag = flagging;
				curData.field = field;
				curData.time = time;
				curData.available = true;
			}
		}
	}
	stopwatch.Pause();
	std::cout << "DONE in " << stopwatch.ToString() << " (" << (stopwatch.Seconds() / (antenna1Domain.ValueCount() * antenna1Domain.ValueCount())) << "s/antenna)" << std::endl;

	std::cout << "Imaging..." << std::flush;
	stopwatch.Reset();
	stopwatch.Start();
	for(unsigned f = 0;f<frequencies.ValueCount();++f) {
		for(unsigned a1 = 0;a1<antenna1Domain.ValueCount();++a1) {
			for(unsigned a2 = 0;a2<antenna2Domain.ValueCount();++a2) {
				Image(frequencies.GetValue(f), _antennas[antenna1Domain.GetValue(a1)], _antennas[antenna2Domain.GetValue(a2)], data[f][a1][a2]);
			}
		}
	}
	stopwatch.Pause();
	std::cout << "DONE in " << stopwatch.ToString() << " (" << (stopwatch.Seconds() / (antenna1Domain.ValueCount() * antenna1Domain.ValueCount())) << "s/antenna)" << std::endl;

	// free data
	for(unsigned f = 0;f<frequencies.ValueCount();++f) {
		for(unsigned a1 = 0;a1<antenna1Domain.ValueCount();++a1) {
			for(unsigned a2 = 0;a2<antenna2Domain.ValueCount();++a2) {
				delete[] data[f][a1][a2];
			}
			delete[] data[f][a1];
		}
		delete[] data[f];
	}
	delete[] data;
}
コード例 #20
0
ファイル: sysutils.cpp プロジェクト: Bhushan1002/SFrame
bool
SocketPool::wait( UInt32 msTimeout, UInt32 msInterruptOnlyTimeout, SocketActions *socketActions )   
{
    dbgAssert( socketActions );
    socketActions->clear();

    if( m_pool->size() == 0 )
    {
        // We don't have any sockets to check activity, so wait for 
        // the interrupt event.

#ifdef PERF
        Stopwatch stopwatch( true );
#endif

        DWORD res = WaitForSingleObject( m_interrupt.m_handle, msInterruptOnlyTimeout );
        dbgAssert( res == WAIT_OBJECT_0 || res == WAIT_TIMEOUT );

#ifdef PERF
        LOG_TRACE( "SocketPoolSync:wait for interrupt, actual=%llu, result=%d", 
            stopwatch.elapsed(), res );
#endif

        m_interrupt.reset();
        return res == WAIT_OBJECT_0;  // true if interrupt.
    }
  
    // It would be great to be able to wait for all sockets and the interrupt event together.
    // But we cannot use WSAPoll for that (because it supports sockets only) and 
    // WSAEventSelect/WaitForMultipleObjects (because they are not usable with curl for
    // write events). 
    //
    // For the latter from MSDN (WSAEventSelect):
    //   The FD_WRITE network event is handled slightly differently. An FD_WRITE network event is recorded 
    //   when a socket is first connected with a call to the connect, ConnectEx, WSAConnect, 
    //   WSAConnectByList, or WSAConnectByName function or when a socket is accepted with accept, 
    //   AcceptEx, or WSAAccept function and then after a send fails with WSAEWOULDBLOCK and 
    //   buffer space becomes available. Therefore, an application can assume that sends are 
    //   possible starting from the first FD_WRITE network event setting and lasting until 
    //   a send returns WSAEWOULDBLOCK. After such a failure the application will find out 
    //   that sends are again possible when an FD_WRITE network event is recorded and the
    //   associated event object is set.
    //
    // We don't know if the curl (or whatever caller) got WSAEWOULDBLOCK or not. And if the event is signaled,
    // we don't know if we need to reset it.
    // If curl didn't get WSAEWOULDBLOCK and we reset the event now,
    // we may not (or will never depending on how we are sending) get another signal for a while. 
    // But if we don't reset, WaitForMultipleObjects(..)
    // call becomes useless because the event is always signaled and we just get a busy loop.
    //
    // Other options such as to invoke APC to interrupt WSAPoll don't work either, APC gets
    // delivered but WSAPoll continues running and not interrupted immediately.
    //
    // As workaround, let's spin with short WSAPoll calls and check the interrupt signal in between
    // them.
    //

    dbgAssert( msTimeout < INFINITE );
    const UInt32 spinTimeout = 15;

    while( msTimeout )
    {
        // Check the interrupt signal.

        if( m_interrupt.wait( 0 ) )
        {
            m_interrupt.reset();
            return true;  // true if interrupt.
        }

#ifdef PERF
        Stopwatch stopwatch( true );
#endif
        int res = WSAPoll( &( ( *m_pool )[ 0 ] ), m_pool->size(), spinTimeout );
#ifdef PERF
        LOG_TRACE( "SocketPoolSync:WSAPoll, timeout left=%d, spin=%d, actual=%llu, size=%llu, result=%d", 
            msTimeout, spinTimeout, stopwatch.elapsed(), static_cast< UInt64 >( m_pool->size() ), res );
#endif

        dbgAssert( res >= 0 );

        if( res == 0 )
        {
            if ( msTimeout <= spinTimeout )
            {
                // Overall timeout has expired.

                break;
            }

            // Reduce the overall timeout and repeat.

            msTimeout -= spinTimeout;
            continue;
        }

        if( res > 0 )
        {
            for( SocketPoolState::const_iterator it = m_pool->begin(); it != m_pool->end(); ++it )
            {
                if( it->revents != 0 )
                {
                    socketActions->push_back( SocketActions::value_type( sh( it->fd ), 
                        getActionMask( it->events, it->revents ) ) );
                }
            }
        }

        break;
    }

    return !socketActions->empty(); // true if activity has been detected.
}
コード例 #21
0
ファイル: build-graph.cpp プロジェクト: ixchow/portmantout
int main(int argc, char **argv) {

	Node root;
	Node *start = nullptr;

	stopwatch("start");

	//initial tree:
	std::ifstream wordlist("wordlist.asc");
	std::string word;
	while (std::getline(wordlist, word)) {
		Node *at = &root;
		for (auto c : word) {
			auto f = at->insert(std::make_pair(c, nullptr)).first;
			if (f->second == NULL) {
				f->second = new Node();
				f->second->parent = at;
				f->second->depth = f->second->parent->depth + 1;
			}
			at = f->second;
		}
		assert(at);
		assert(at->terminal == false);
		at->terminal = true;
		if (word == "portmanteau") {
			start = at;
		}
	}
	assert(start);

	stopwatch("read");

	//set rewind pointers:
	{
		std::vector< Node * > layer;
		layer.push_back(&root);
		while (!layer.empty()) {
			std::vector< Node * > next_layer;
			for (auto n : layer) {
				//update rewind pointers for children based on current rewind pointer.
				for (auto cn : *n) {
					next_layer.emplace_back(cn.second);

					//rewind:
					Node *r = n->rewind;
					while (r != nullptr) {
						assert(r != nullptr);
						auto f = r->find(cn.first);
						if (f != r->end()) {
							//great, can extend this rewind:
							r = f->second;
							break;
						} else {
							//have to rewind further:
							r = r->rewind;
						}
					}
					assert(n == &root || r != nullptr); //for everything but the root, rewind should always hit root and bounce down
					if (r == nullptr) r = &root;
					cn.second->rewind = r;
				}
			}
			layer = next_layer;
		}
	}

	{ //dump some info about the tree:
		uint32_t nodes = 0;
		uint32_t edges = 0;
		uint32_t rewinds = 0;
		uint32_t terminal = 0;
		uint32_t steps = 0;
		std::function< void(Node *) > count = [&](Node *n) {
			nodes += 1;
			if (n->rewind) rewinds += 1;
			if (n->terminal) terminal += 1;
			for (auto &c : *n) {
				steps += 1;
				edges += 1;
				if (c.first != '\0') {
					count(c.second);
				}
			}
			//add valid next steps from rewind pointers:
			if (n->terminal) {
				for (Node *r = n->rewind; r != &root; r = r->rewind) {
					assert(r);
					steps += r->size();
				}
			}
		};
		count(&root);
		std::cout << "Built tree with " << nodes << " nodes and " << edges << " edges." << std::endl;
		std::cout << "Have " << terminal << " terminal nodes." << std::endl;
		std::cout << "Have " << rewinds << " rewind pointers." << std::endl;
		std::cout << "Have " << steps << " 'next step' edges (includes rewinds at terminals)." << std::endl;
	}

	//set indices:
	std::vector< Node * > nodes;
	uint32_t adjacencies = 0;
	uint32_t children = 0;
	{
		std::function< void(Node *) > index = [&](Node *n) {
			n->index = nodes.size();
			nodes.emplace_back(n);

			children += n->size();
			adjacencies += n->size();
			//add valid next steps from rewind pointers:
			if (n->terminal) {
				for (Node *r = n->rewind; r != &root; r = r->rewind) {
					assert(r);
					adjacencies += r->size();
				}
			}
			for (auto cn : *n) {
				index(cn.second);
			}
		};
		index(&root);
	}

	for (auto n : nodes) {
		if (n->terminal && n->size() == 0) n->maximal = true;
	}
	{
		uint32_t maximal = 0;
		for (auto n : nodes) {
			if (n->maximal) ++maximal;
		}
		std::cout << "Have " << maximal << " maximal words based on child counting." << std::endl;
	}
	for (auto n : nodes) {
		if (n->rewind) n->rewind->maximal = false;
	}
	{
		uint32_t maximal = 0;
		for (auto n : nodes) {
			if (n->maximal) ++maximal;
		}
		std::cout << "Have " << maximal << " maximal words after rewind culling." << std::endl;
	}

	//okay, a valid step is:
	// - (at any node) a marked next letter for this node
	// - (at a terminal node) a marked next letter for some [non-root!] rewind of this node

	Graph graph;
	graph.resize(nodes.size(), adjacencies, children);

	{
		auto adj_start = graph.adj_start;
		auto adj = graph.adj;
		auto adj_char = graph.adj_char;

		auto child_start = graph.child_start;
		auto child = graph.child;
		auto child_char = graph.child_char;

		for (auto const &n : nodes) {
			assert(&n - &nodes[0] == n->index);
			*(adj_start++) = adj - graph.adj;
			*(child_start++) = child - graph.child;
			std::vector< std::pair< char, Node * > > valid(n->begin(), n->end());
			std::stable_sort(valid.begin(), valid.end());
			for (auto v : valid) {
				*(child_char++) = v.first;
				*(child++) = v.second->index;
			}
			if (n->terminal) {
				for (Node *r = n->rewind; r != &root; r = r->rewind) {
					assert(r);
					valid.insert(valid.end(), r->begin(), r->end());
				}
			}
			std::stable_sort(valid.begin(), valid.end());
			for (auto v : valid) {
				*(adj_char++) = v.first;
				*(adj++) = v.second->index;
			}
		}
		*(adj_start++) = adj - graph.adj;
		*(child_start++) = child - graph.child;

		assert(adj == graph.adj + adjacencies);
		assert(adj_char == graph.adj_char + adjacencies);
		assert(adj_start == graph.adj_start + nodes.size() + 1);

		assert(child == graph.child + children);
		assert(child_char == graph.child_char + children);
		assert(child_start == graph.child_start + nodes.size() + 1);
	}

	{
		auto depth = graph.depth;
		auto maximal = graph.maximal;
		auto parent = graph.parent;
		auto rewind = graph.rewind;

		for (uint32_t i = 0; i < nodes.size(); ++i) {
			assert(nodes[i]->index == i);
			*(depth++) = nodes[i]->depth;
			*(maximal++) = nodes[i]->maximal;
			if (nodes[i]->parent) {
				*(parent++) = nodes[i]->parent->index;
			} else {
				assert(i == 0);
				*(parent++) = -1U;
			}
			if (nodes[i]->rewind) {
				*(rewind++) = nodes[i]->rewind->index;
			} else {
				*(rewind++) = -1U;
			}
		}
		assert(depth   == graph.depth + nodes.size());
		assert(maximal == graph.maximal + nodes.size());
		assert(parent  == graph.parent + nodes.size());
		assert(rewind  == graph.rewind + nodes.size());
	}

	stopwatch("build");

	graph.write("wordlist.graph");

	stopwatch("write");

	return 0;
}
コード例 #22
0
ファイル: physEngine.cpp プロジェクト: mikowiec/harvest
void Engine::update_world(double start_time, double delta_time)
{
	frame_stop = start_time + delta_time;

	double start = stopwatch();
	
	bucVec keys;
	bucVec new_keys;
	bucVec obsolete_keys;
	

	//Update the hashboxes for all dynamic objects
	for(dyn_iterator dyn_it = wr->begin_dyn();dyn_it != wr->end_dyn(); ++dyn_it){
	
		reaper::object::phys::ObjectAccessor &phys_acc = dyn_it->get_physics();
		
		const double len = length(phys_acc.vel)*delta_time;

		const double ext1 = phys_acc.radius + len + 
			 phys_acc.max_acc * delta_time* delta_time / 2;
		
		const double ext2 = ext1 - 2* len;

		const Point &pos = dyn_it->get_pos(); 
		
		Point pt1( pos + norm(phys_acc.vel)*ext1 );
		Point pt2( pos - norm(phys_acc.vel)*ext2 );

		const Point p1(min(pt1.x,pt2.x),min(pt1.y,pt2.y), min(pt1.z,pt2.z) );
		const Point p2(max(pt1.x,pt2.x), max(pt1.y,pt2.y), max(pt1.z,pt2.z) );

		the_grid.calc_key(p1,p2,keys);		
		
		bucVec& current_k = old_keys[dyn_it->get_id()];
				
		for(int i = 0;i < keys.size(); ++i){
			bucVec::const_iterator p = 
				find(current_k.begin(), current_k.end(), keys[i] );
			
			if(p == current_k.end() )
				new_keys.push_back(keys[i]);
		}
		
		for(int i = 0;i < current_k.size(); ++i){
			bucVec::const_iterator p2 = 
				find(keys.begin(), keys.end(), current_k[i] );
			
			if(p2 == keys.end() )
				obsolete_keys.push_back(keys[i]);
		}

		for(int i = 0;i < new_keys.size();++i){
			collision_table.insert(dyn_it->get_id(),new_keys[i]);
			const set<int>& ids = collision_table.get_ids(new_keys[i]);
			for(std::set<int>::const_iterator j = ids.begin();j != ids.end(); ++j){
				int res = close_pairs.increase(dyn_it->get_id(),*j);
				if(res == 1){
					Pair* pr;
					SillyPtr si = wr->lookup_si(*j);
					StaticPtr st = wr->lookup_st(*j);
					DynamicPtr dyn = wr->lookup_dyn(*j);
					ShotPtr sh = wr->lookup_shot(*j);
					if( si.valid() ){
						pr = new SillyDynPair(si,*dyn_it);
					}
					else if( st.valid() )
						pr = new StaticDynPair(st,*dyn_it);
					else if( dyn.valid() )
						pr = new DynDynPair(dyn,*dyn_it);
					else if( sh.valid() )
						pr = new ShotDynPair(sh,*dyn_it);
					pr->calc_lower_bound();
					prio_queue.insert(pr);
				}
			}
		}
		
		
		
		for(int i = 0;i < obsolete_keys.size();++i){
			collision_table.remove(dyn_it->get_id(),obsolete_keys[i]);
			const set<int> ids = collision_table.get_ids(new_keys[i]);
			for(std::set<int>::const_iterator j = ids.begin();j != ids.end(); ++j){
				close_pairs.decrease(dyn_it->get_id(),*j);
			}
		}

		

		new_keys.clear();
		obsolete_keys.clear();

	}

	double mid = stopwatch();
	
	if(!prio_queue.empty()) {
		while( !prio_queue.empty() && prio_queue.top()->get_lower_bound() < frame_stop ) {
			
			//Now check if we want to simulate a collision between objects                                 
			Pair* pair = prio_queue.top();
			
			double dt = pair->get_lower_bound() - pair->get_sim_time();
			
			if(dt < 0)
				cout << "Neg dt!" << endl;

			//the object will be simulated this far when the loop has ended

			//prio_queue.pop();
			//Pair simulate simulates until lower_bound                                   
			pair->simulate( pair->get_lower_bound() );                                        
			
			if(pair->check_distance() < Collision_Distance ) {                                                
				if (pair->collide( *(pair->get_collision()) ) ) 
					prio_queue.update_if(tstId(pair->get_id1(), pair->get_id2() ));
			}
						
			if( to_insert(frame_stop,*pair) ) {
				pair->calc_lower_bound();
				prio_queue.update(pair);
				
			}
			else{
				prio_queue.pop();
				delete pair;
			}
	

		}

	}
		

	double mid2 = stopwatch();

	//Now simulate all objects until framestop
	//Simulate all aobjekt so that they have a simtime of end of fram
	
	
	for(dyn_iterator i(wr->begin_dyn()); i != wr->end_dyn(); ++i){
		double dt = frame_stop - i->get_sim_time();
		if(dt < 0 ) 
			cout << "Negative dt!" << dt <<endl;
		i->simulate(dt);
	}

	double end = stopwatch();

	cout << "Timing info Hash: " << mid - start << " treap: " << mid2 - mid << endl;

	/*
	for(st_iterator i(wr->begin_st()); i != wr->end_st(); ++i){
		double dt = frame_stop - i->get_sim_time();
		i->simulate(dt);
	}
	
	for(shot_iterator i(wr->begin_shot()); i != wr->end_shot(); ++i){
		double dt = frame_stop - i->get_sim_time();
		i->simulate(dt);
	}

	*/
	
	
}
コード例 #23
0
ファイル: sysutils.cpp プロジェクト: Bhushan1002/SFrame
bool
SocketPool::wait( UInt32 msTimeout, UInt32 msInterruptOnlyTimeout, SocketActions *socketActions )
{
    dbgAssert( socketActions );
    socketActions->clear();

    int res = 0;

    // If we have at least one socket, make sure that timeout is not infinite,
    // see the comments in the add(..) method.
    dbgAssert( !m_pool->sockets.size() || msTimeout < ( UInt32 ) -1 );

    UInt32 initTimeout = m_pool->sockets.size() > 0 ? msTimeout : msInterruptOnlyTimeout;
    Timeout timeout( initTimeout ); 

    bool interrupt_triggered = false;
    while( true ) 
    {
#ifdef PERF
        Stopwatch stopwatch( true );
#endif
        for (size_t i = 0;i < m_pool->polllist.size(); ++i) {
          m_pool->polllist[i].revents = 0;
        }
        // 15ms timeout
        res = poll( m_pool->polllist.data(), m_pool->polllist.size(), 15);

#ifdef PERF
        LOG_TRACE( "SocketPoolSync:poll_wait, timeout=%d, actual=%llu, size=%llu, result=%d", 
            initTimeout, stopwatch.elapsed(), static_cast< UInt64 >( m_pool->sockets.size() ), res );
#endif
        if (m_interrupt.get_state()) interrupt_triggered = true;
        if( res == -1 )
        {
            int e = errno;

            if( e == EINTR )
            {
                // Make sure we don't end up in infinite loop when timeout is not infinite.

                if( timeout.left() )
                    continue;

                break;
            }

            if( e == ENOMEM )
            {
                // Out of memory, we cannot do anything better than just wait for a while.

                taskSleep( 3000 );
                break;
            }

            dbgPanicSz( "BUG: poll_wait failed!!!" );
        }

        break;
    } 

    // Get the events.

    if (interrupt_triggered) m_interrupt.reset();
    size_t eventCount = 0;
    for (size_t i = 0;i < m_pool->polllist.size(); ++i) {
      if (m_pool->polllist[i].revents != 0) {
        socketActions->push_back( SocketActions::value_type( m_pool->polllist[i].fd,
                                                          getActionMask( m_pool->polllist[i].revents ) ) );
        ++eventCount;
      }
    }

    return eventCount != 0;  // true if socket activity or interrupt.
}
コード例 #24
0
ファイル: benchmarksuite.cpp プロジェクト: Lorenz25/appleseed
void BenchmarkSuite::run(
    const IFilter&      filter,
    BenchmarkResult&    suite_result) const
{
    BenchmarkingThreadContext benchmarking_context;
    bool has_begun_suite = false;

    for (size_t i = 0; i < impl->m_factories.size(); ++i)
    {
        IBenchmarkCaseFactory* factory = impl->m_factories[i];

        // Skip benchmark cases that aren't let through by the filter.
        if (!filter.accepts(factory->get_name()))
            continue;

        if (!has_begun_suite)
        {
            // Tell the listeners that a benchmark suite is about to be executed.
            suite_result.begin_suite(*this);
            suite_result.signal_suite_execution();
            has_begun_suite = true;
        }

        // Instantiate the benchmark case.
        auto_ptr<IBenchmarkCase> benchmark(factory->create());

        // Recreate the stopwatch (and the underlying timer) for every benchmark
        // case, since the CPU frequency will fluctuate quite a bit depending on
        // the CPU load.  We need an up-to-date frequency estimation in order to
        // compute accurate call rates.
        Impl::StopwatchType stopwatch(100000);

        // Tell the listeners that a benchmark case is about to be executed.
        suite_result.begin_case(*this, *benchmark.get());

#ifdef NDEBUG
        try
#endif
        {
            suite_result.signal_case_execution();

            // Estimate benchmarking parameters.
            Impl::BenchmarkParams params;
            Impl::estimate_benchmark_params(
                benchmark.get(),
                stopwatch,
                params);

            // Measure the overhead of calling IBenchmarkCase::run().
            const double overhead =
                Impl::measure_call_overhead(stopwatch, params);

            // Run the benchmark case.
            const double execution_time =
                Impl::measure_iteration_runtime(
                    benchmark.get(),
                    stopwatch,
                    params);

            // Gather the timing results.
            TimingResult timing_result;
            timing_result.m_iteration_count = params.m_iteration_count;
            timing_result.m_measurement_count = params.m_measurement_count;
            timing_result.m_frequency = static_cast<double>(stopwatch.get_timer().frequency());
            timing_result.m_ticks = execution_time > overhead ? execution_time - overhead : 0.0;

            // Post the timing result.
            suite_result.write(
                *this,
                *benchmark.get(),
                __FILE__,
                __LINE__,
                timing_result);
        }
#ifdef NDEBUG
        catch (const exception& e)
        {
            suite_result.write(
                *this,
                *benchmark.get(),
                __FILE__,
                __LINE__,
                "an unexpected exception was caught: %s.",
                e.what());

            suite_result.signal_case_failure();
        }
        catch (...)
        {
            suite_result.write(
                *this,
                *benchmark.get(),
                __FILE__,
                __LINE__,
                "an unexpected exception was caught (no details available).");

            suite_result.signal_case_failure();
        }
#endif

        // Tell the listeners that the benchmark case execution has ended.
        suite_result.end_case(*this, *benchmark.get());
    }

    if (has_begun_suite)
    {
        // Report a benchmark suite failure if one or more benchmark cases failed.
        if (suite_result.get_case_failure_count() > 0)
            suite_result.signal_suite_failure();

        // Tell the listeners that the benchmark suite execution has ended.
        suite_result.end_suite(*this);
    }
}
コード例 #25
0
ファイル: ValidatorManager.cpp プロジェクト: E-LLP/rippled
 std::unique_ptr<Connection>
 newConnection (int id) override
 {
     return std::make_unique<ConnectionImp>(
         id, logic_, stopwatch());
 }
コード例 #26
0
ファイル: benchmarksuite.cpp プロジェクト: dcoeurjo/appleseed
void BenchmarkSuite::run(
    const IFilter&      filter,
    BenchmarkResult&    suite_result) const
{
    BenchmarkingThreadContext benchmarking_context;
    bool has_begun_suite = false;

    for (size_t i = 0; i < impl->m_factories.size(); ++i)
    {
        IBenchmarkCaseFactory* factory = impl->m_factories[i];

        // Skip benchmark cases that aren't let through by the filter.
        if (!filter.accepts(factory->get_name()))
            continue;

        if (!has_begun_suite)
        {
            // Tell the listeners that a benchmark suite is about to be executed.
            suite_result.begin_suite(*this);
            suite_result.signal_suite_execution();
            has_begun_suite = true;
        }

        // Instantiate the benchmark case.
        unique_ptr<IBenchmarkCase> benchmark(factory->create());

        // Recreate the stopwatch (and the underlying timer) for every benchmark
        // case, since the CPU frequency will fluctuate quite a bit depending on
        // the CPU load.  We need an up-to-date frequency estimation in order to
        // compute accurate call rates.
        Impl::StopwatchType stopwatch(100000);

        // Tell the listeners that a benchmark case is about to be executed.
        suite_result.begin_case(*this, *benchmark.get());

#ifdef NDEBUG
        try
#endif
        {
            suite_result.signal_case_execution();

            // Estimate benchmarking parameters.
            const size_t measurement_count =
                Impl::compute_measurement_count(benchmark.get(), stopwatch);

            // Measure the overhead of calling IBenchmarkCase::run().
            const double overhead_ticks =
                Impl::measure_call_overhead_ticks(stopwatch, measurement_count);

            // Run the benchmark case.
            const double runtime_ticks =
                Impl::measure_runtime(
                    benchmark.get(),
                    stopwatch,
                    BenchmarkSuite::Impl::measure_runtime_ticks,
                    measurement_count);

#ifdef GENERATE_BENCHMARK_PLOTS
            vector<Vector2d> points;

            for (size_t j = 0; j < 100; ++j)
            {
                const double ticks =
                    Impl::measure_runtime(
                        benchmark.get(),
                        stopwatch,
                        BenchmarkSuite::Impl::measure_runtime_ticks,
                        max<size_t>(1, measurement_count / 100));
                points.emplace_back(
                    static_cast<double>(j),
                    ticks > overhead_ticks ? ticks - overhead_ticks : 0.0);
            }

            stringstream sstr;
            sstr << "unit benchmarks/plots/";
            sstr << get_name() << "_" << benchmark->get_name();
            sstr << ".gnuplot";

            GnuplotFile plotfile;
            plotfile.new_plot().set_points(points);
            plotfile.write(sstr.str());
#endif

            // Gather the timing results.
            TimingResult timing_result;
            timing_result.m_iteration_count = 1;
            timing_result.m_measurement_count = measurement_count;
            timing_result.m_frequency = static_cast<double>(stopwatch.get_timer().frequency());
            timing_result.m_ticks = runtime_ticks > overhead_ticks ? runtime_ticks - overhead_ticks : 0.0;

            // Post the timing result.
            suite_result.write(
                *this,
                *benchmark.get(),
                __FILE__,
                __LINE__,
                timing_result);
        }
#ifdef NDEBUG
        catch (const exception& e)
        {
            if (e.what()[0] != '\0')
            {
                suite_result.write(
                    *this,
                    *benchmark.get(),
                    __FILE__,
                    __LINE__,
                    "an unexpected exception was caught: %s",
                    e.what());
            }
            else
            {
                suite_result.write(
                    *this,
                    *benchmark.get(),
                    __FILE__,
                    __LINE__,
                    "an unexpected exception was caught (no details available).");
            }

            suite_result.signal_case_failure();
        }
        catch (...)
        {
            suite_result.write(
                *this,
                *benchmark.get(),
                __FILE__,
                __LINE__,
                "an unexpected exception was caught (no details available).");

            suite_result.signal_case_failure();
        }
#endif

        // Tell the listeners that the benchmark case execution has ended.
        suite_result.end_case(*this, *benchmark.get());
    }

    if (has_begun_suite)
    {
        // Report a benchmark suite failure if one or more benchmark cases failed.
        if (suite_result.get_case_failure_count() > 0)
            suite_result.signal_suite_failure();

        // Tell the listeners that the benchmark suite execution has ended.
        suite_result.end_suite(*this);
    }
}
コード例 #27
0
ファイル: simulator_driver.c プロジェクト: T-R0D/Past-Courses
int manageIoDevice( Device* device, Heap* ready_queue,
                    ActivityLog* activity_log )
{
    // variables
    char action_message[STD_STR_LEN];
    PCB temp;

    // case: an I/O completion interrupt has been raised
    if( device->data.interrupt_flag )
    {
        // time this action
        stopwatch( 's', IO_TIMER );

        // kill the I/O simulating thread
        pthread_join( device->data.thread_id, NULL );

        // release the device from the process, load it into the main
        // scheduler
        device->data.interrupt_flag = false;
        device->data.in_use = false;
        insert_heap( ready_queue, *(device->working_process), FIFO_HEAP );
        device->working_process = NULL;

        // log this action
        sprintf( action_message, "%s action completed for process %d - "
                                 "process placed back in main scheduler",
                 device->name, device->working_process->pid );
        logEvent( activity_log, SYSTEM, action_message,
                   stopwatch( 'x', IO_TIMER ) );
    }
    // case: an I/O processed is running and needs to be managed
    else if( device->data.in_use )
    {
        // log the maintenance of the process (simulate with a short wait)
        stopwatch( 's', IO_TIMER );
        usleep( IO_MANAGEMENT_TIME );
        sprintf( action_message,
                 "I/O maintnenance: %s still in use by process %d",
                 device->name, device->working_process->pid );
        logEvent( activity_log, SYSTEM, action_message,
                   stopwatch( 'x', IO_TIMER ) );
    }

    // case: an I/O process is wating to run and the I/O device is free
    //       (it is possible that the device was previously freed previously)
    if( !(device->data.in_use) && !is_Heap_empty( &(device->waiting_queue ) ) )
    {
        // start the I/O process on this device
        stopwatch( 's', IO_TIMER );
        temp = remove_PCB_from_Heap( &(device->waiting_queue) );
        device->working_process = &temp;

        // startup the independent I/O action (simulated of course)
        pthread_attr_init( &(device->data.attribute) );
        pthread_create( &(device->data.thread_id), &(device->data.attribute),
                        conductIoProcess, (void*) &(device->data) );

        // log the action
        sprintf( action_message, "Starting process %d on %s",
                 device->working_process->pid, device->name );
        logEvent( activity_log, SYSTEM, action_message,
                  stopwatch( 'x', IO_TIMER ) );
    }
}
コード例 #28
0
int main(int argc, char **argv) {

	stopwatch("start");
	Graph graph;
	if (!graph.read("wordlist.graph")) {
		std::cerr << "Failed to read graph." << std::endl;
		exit(1);
	}
	stopwatch("read graph");

	std::vector< uint32_t > maximal;

	for (auto m = graph.maximal; m != graph.maximal + graph.nodes; ++m) {
		if (*m) {
			maximal.emplace_back(m - graph.maximal);
		}
	}
	std::cout << "Have " << maximal.size() << " maximal nodes." << std::endl;

	std::unique_ptr< uint8_t[] > distances(new uint8_t[maximal.size() * maximal.size()]);

	stopwatch("setup");

	//run lots of BFS's:
	for (auto const &seed : maximal) {
		std::vector< uint8_t > distance(graph.nodes, 0xff);
		std::vector< uint32_t > ply;
		ply.emplace_back(seed);
		distance[seed] = 0;
		uint32_t dis = 0;
		while (!ply.empty()) {
			std::vector< uint32_t > next_ply;
			dis += 1;
			assert(dis < 0xff);
			for (auto i : ply) {
				for (uint32_t a = graph.adj_start[i]; a < graph.adj_start[i+1]; ++a) {
					uint32_t n = graph.adj[a];
					if (distance[n] == 0xff) {
						distance[n] = dis;
						next_ply.emplace_back(n);
					}
				}
			}
			ply = std::move(next_ply);
		}

		static uint8_t max = 0;

		{ //copy to distances table
			uint8_t *base = distances.get() + (&seed - &maximal[0]) * maximal.size();
			for (auto const &m : maximal) {
				assert(distance[m] != 0xff);
				max = std::max(max, distance[m]);
				*(base++) = distance[m];
			}
		}

		static uint32_t step = 0;
		step += 1;
		if (step == 500) {
			stopwatch("bfs * 500");
			std::cout << (&seed - &maximal[0]) << " / " << maximal.size()
				<< " -- longest path so far: " << int32_t(max) << "."
				<< std::endl;
			step = 0;
		}
	}

	stopwatch("last bit of calculation");

	std::ofstream out("distances.table");
	out.write(reinterpret_cast< const char * >(distances.get()), maximal.size() * maximal.size());

	stopwatch("write");

	return 0;
}