这篇教程C++ timer函数代码示例写得很实用,希望能帮到您。
本文整理汇总了C++中timer函数的典型用法代码示例。如果您正苦于以下问题:C++ timer函数的具体用法?C++ timer怎么用?C++ timer使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。 在下文中一共展示了timer函数的29个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。 示例1: DoPumpsize_t NonblockingSource::GeneralPump2( lword& byteCount, bool blockingOutput, unsigned long maxTime, bool checkDelimiter, byte delimiter){ m_blockedBySpeedLimit = false; if (!GetMaxBytesPerSecond()) { size_t ret = DoPump(byteCount, blockingOutput, maxTime, checkDelimiter, delimiter); m_doPumpBlocked = (ret != 0); return ret; } bool forever = (maxTime == INFINITE_TIME); unsigned long timeToGo = maxTime; Timer timer(Timer::MILLISECONDS, forever); lword maxSize = byteCount; byteCount = 0; timer.StartTimer(); while (true) { lword curMaxSize = UnsignedMin(ComputeCurrentTransceiveLimit(), maxSize - byteCount); if (curMaxSize || m_doPumpBlocked) { if (!forever) timeToGo = SaturatingSubtract(maxTime, timer.ElapsedTime()); size_t ret = DoPump(curMaxSize, blockingOutput, timeToGo, checkDelimiter, delimiter); m_doPumpBlocked = (ret != 0); if (curMaxSize) { NoteTransceive(curMaxSize); byteCount += curMaxSize; } if (ret) return ret; } if (maxSize != ULONG_MAX && byteCount >= maxSize) break; if (!forever) { timeToGo = SaturatingSubtract(maxTime, timer.ElapsedTime()); if (!timeToGo) break; } double waitTime = TimeToNextTransceive(); if (!forever && waitTime > timeToGo) { m_blockedBySpeedLimit = true; break; } WaitObjectContainer container; LimitedBandwidth::GetWaitObjects(container, CallStack("NonblockingSource::GeneralPump2() - speed limit", 0)); container.Wait((unsigned long)waitTime); } return 0;}
开发者ID:Andy-Amoy,项目名称:cryptopp,代码行数:63,
示例2: mainint main() { GDT::init(); Console::init(); IDT::init(); ExceptionHandler::init_dispatcher(); IRQ::init(); InterruptHandler::init_dispatcher(); /* -- EXAMPLE OF AN EXCEPTION HANDLER -- */ class DBZ_Handler : public ExceptionHandler { public: virtual void handle_exception(REGS * _regs) { Console::puts("DIVISION BY ZERO!/n"); for(;;); } } dbz_handler; ExceptionHandler::register_handler(0, &dbz_handler); /* -- INITIALIZE MEMORY -- */ /* NOTE: We don't have paging enabled in this MP. */ /* NOTE2: This is not an exercise in memory management. The implementation of the memory management is accordingly *very* primitive! */ /* ---- Initialize a frame pool; details are in its implementation */ FramePool system_frame_pool; SYSTEM_FRAME_POOL = &system_frame_pool; /* ---- Create a memory pool of 256 frames. */ MemPool memory_pool(SYSTEM_FRAME_POOL, 256); MEMORY_POOL = &memory_pool; /* -- INITIALIZE THE TIMER (we use a very simple timer).-- */ /* Question: Why do we want a timer? We have it to make sure that we enable interrupts correctly. If we forget to do it, the timer "dies". */ SimpleTimer timer(100); /* timer ticks every 10ms. */ InterruptHandler::register_handler(0, &timer); /* The Timer is implemented as an interrupt handler. */#ifdef _USES_SCHEDULER_ /* -- SCHEDULER -- IF YOU HAVE ONE -- */ Scheduler system_scheduler = Scheduler(); SYSTEM_SCHEDULER = &system_scheduler;#endif #ifdef _USES_DISK_ /* -- DISK DEVICE -- IF YOU HAVE ONE -- */ //SimpleDisk system_disk = SimpleDisk(MASTER, SYSTEM_DISK_SIZE); BlockingDisk system_disk = BlockingDisk(MASTER, SYSTEM_DISK_SIZE); SYSTEM_DISK = &system_disk;#endif#ifdef _USES_FILESYSTEM_ /* -- FILE SYSTEM -- IF YOU HAVE ONE -- */ FileSystem file_system = FileSystem(); FILE_SYSTEM = &file_system;#endif /* NOTE: The timer chip starts periodically firing as soon as we enable interrupts. It is important to install a timer handler, as we would get a lot of uncaptured interrupts otherwise. */ /* -- ENABLE INTERRUPTS -- */ machine_enable_interrupts(); /* -- MOST OF WHAT WE NEED IS SETUP. THE KERNEL CAN START. */ Console::puts("Hello World!/n"); /* -- LET'S CREATE SOME THREADS... */ Console::puts("CREATING THREAD 1.../n"); char * stack1 = new char[1024]; thread1 = new Thread(fun1, stack1, 1024); Console::puts("DONE/n"); Console::puts("CREATING THREAD 2..."); char * stack2 = new char[4096]; thread2 = new Thread(fun2, stack2, 4096); Console::puts("DONE/n"); Console::puts("CREATING THREAD 3..."); char * stack3 = new char[8192];//.........这里部分代码省略.........
开发者ID:tharun-b,项目名称:Kernel_OS,代码行数:101,
示例3: reduce_test//.........这里部分代码省略......... reduce.cmd.xfer_reduce.rtypecount = 0; int op, dt; for (dt = 0; dt < dt_count; dt++) { for (op = 0; op < op_count; op++) { if (gValidTable[op][dt]) { if (my_ep == zero_ep) printf("Running Reduce: %s, %s/n", dt_array_str[dt], op_array_str[op]); int i; for (i = MAX(1,gMin_byte_count/get_type_size(dt_array[dt])); i <= gMax_byte_count/get_type_size(dt_array[dt]); i *= 2) { size_t sz=get_type_size(dt_array[dt]); size_t dataSent = i * sz; int niter; if (dataSent < CUTOFF) niter = gNiterlat; else niter = NITERBW; reduce.cmd.xfer_reduce.stypecount = i; reduce.cmd.xfer_reduce.rtypecount = dataSent; reduce.cmd.xfer_reduce.stype = dt_array[dt]; reduce.cmd.xfer_reduce.op = op_array[op]; reduce_initialize_sndbuf (sbuf, i, op, dt, td->logical_rank, num_ep); memset(rbuf, 0xFF, dataSent); blocking_coll(myContext, &barrier, &bar_poll_flag); ti = timer(); pami_task_t root_task = 0; int j, ctxt_id = 0; /* Performance run*/ for (j = 0; j < niter; j++) { pami_endpoint_t root_ep; PAMI_Endpoint_create(client, root_task, ctxt_id, &root_ep); reduce.cmd.xfer_reduce.root = root_ep; if (my_ep == root_ep) reduce.cmd.xfer_reduce.rcvbuf = rbuf; else reduce.cmd.xfer_reduce.rcvbuf = NULL; blocking_coll(myContext, &reduce, &reduce_poll_flag); ctxt_id = (ctxt_id + 1)%gNum_contexts; if(ctxt_id == 0) root_task = (root_task +1)%num_tasks; } tf = timer(); blocking_coll(myContext, &barrier, &bar_poll_flag); /* Correctness*/ reduce_initialize_sndbuf (sbuf, i, op, dt, td->logical_rank, num_ep); memset(rbuf, 0xFF, dataSent); ctxt_id=0; root_task=0; for(j =0; j<gNum_contexts*num_tasks; j++) { pami_endpoint_t root_ep; PAMI_Endpoint_create(client, root_task, ctxt_id, &root_ep); reduce.cmd.xfer_reduce.root = root_ep;
开发者ID:jeffhammond,项目名称:ospri,代码行数:67,
示例4: Q_ASSERT bool Executer::startExecution(bool onlySelection) { Q_ASSERT(mScriptAgent); Q_ASSERT(mScriptEngine); #ifdef ACT_PROFILE Tools::HighResolutionTimer timer("Executer::startExecution"); #endif Code::CodeTools::addClassToScriptEngine<CodeActiona>("Actiona", mScriptEngine); CodeActiona::setActExec(mIsActExec); CodeActiona::setActionaVersion(mActionaVersion); CodeActiona::setScriptVersion(mScriptVersion); Code::CodeTools::addClassGlobalFunctionToScriptEngine("Actiona", &CodeActiona::version, "version", mScriptEngine); Code::CodeTools::addClassGlobalFunctionToScriptEngine("Actiona", &CodeActiona::scriptVersion, "scriptVersion", mScriptEngine); Code::CodeTools::addClassGlobalFunctionToScriptEngine("Actiona", &CodeActiona::isActExec, "isActExec", mScriptEngine); Code::CodeTools::addClassGlobalFunctionToScriptEngine("Actiona", &CodeActiona::isActiona, "isActiona", mScriptEngine); mScriptAgent->setContext(ScriptAgent::ActionInit); CodeInitializer::initialize(mScriptEngine, mScriptAgent, mActionFactory); mScriptAgent->setContext(ScriptAgent::Parameters); QScriptValue script = mScriptEngine->newObject(); mScriptEngine->globalObject().setProperty("Script", script, QScriptValue::ReadOnly); script.setProperty("nextLine", 1); script.setProperty("line", 1, QScriptValue::ReadOnly); QScriptValue callProcedureFun = mScriptEngine->newFunction(callProcedureFunction); callProcedureFun.setData(mScriptEngine->newQObject(this)); script.setProperty("callProcedure", callProcedureFun); QScriptValue console = mScriptEngine->newObject(); mScriptEngine->globalObject().setProperty("Console", console, QScriptValue::ReadOnly); QScriptValue function = mScriptEngine->newFunction(printFunction); function.setData(mScriptEngine->newQObject(this)); console.setProperty("print", function); function = mScriptEngine->newFunction(printWarningFunction); function.setData(mScriptEngine->newQObject(this)); console.setProperty("printWarning", function); function = mScriptEngine->newFunction(printErrorFunction); function.setData(mScriptEngine->newQObject(this)); console.setProperty("printError", function); function = mScriptEngine->newFunction(clearConsoleFunction); function.setData(mScriptEngine->newQObject(this)); console.setProperty("clear", function); mExecuteOnlySelection = onlySelection; mCurrentActionIndex = 0; mActiveActionsCount = 0; mExecutionPaused = false; bool initSucceeded = true; int lastBeginProcedure = -1; mScript->clearProcedures(); mScript->clearCallStack(); const QHash<QString, ActionTools::Resource> &resources = mScript->resources(); for(const QString &key: resources.keys()) { const ActionTools::Resource &resource = resources.value(key); QScriptValue value; switch(resource.type()) { case ActionTools::Resource::BinaryType: case ActionTools::Resource::TypeCount: value = Code::RawData::constructor(resource.data(), mScriptEngine); break; case ActionTools::Resource::TextType: value = QString::fromUtf8(resource.data(), resource.data().size()); break; case ActionTools::Resource::ImageType: { QImage image; if(!image.loadFromData(resource.data())) { mConsoleWidget->addResourceLine(tr("Invalid image resource"), key, ActionTools::ConsoleWidget::Error); return false; } value = Code::Image::constructor(image, mScriptEngine); } break; } mScriptEngine->globalObject().setProperty(key, value, QScriptValue::ReadOnly | QScriptValue::Undeletable); } for(int actionIndex = 0; actionIndex < mScript->actionCount(); ++actionIndex) { ActionTools::ActionInstance *actionInstance = mScript->actionAt(actionIndex); actionInstance->reset(); actionInstance->clearRuntimeParameters(); actionInstance->setupExecution(mScriptEngine, mScript, actionIndex);//.........这里部分代码省略.........
开发者ID:WeDo30,项目名称:actiona,代码行数:101,
示例5: timervoid EngineMaster::processChannels(int iBufferSize) { m_activeBusChannels[EngineChannel::LEFT].clear(); m_activeBusChannels[EngineChannel::CENTER].clear(); m_activeBusChannels[EngineChannel::RIGHT].clear(); m_activeHeadphoneChannels.clear(); m_activeTalkoverChannels.clear(); m_activeChannels.clear(); ScopedTimer timer("EngineMaster::processChannels"); EngineChannel* pMasterChannel = m_pMasterSync->getMaster(); // Reserve the first place for the master channel which // should be processed first m_activeChannels.append(NULL); int activeChannelsStartIndex = 1; // Nothing at 0 yet for (int i = 0; i < m_channels.size(); ++i) { ChannelInfo* pChannelInfo = m_channels[i]; EngineChannel* pChannel = pChannelInfo->m_pChannel; // Skip inactive channels. if (!pChannel || !pChannel->isActive()) { continue; } if (pChannel->isTalkoverEnabled()) { // talkover is an exclusive channel // once talkover is enabled it is not used in // xFader-Mix m_activeTalkoverChannels.append(pChannelInfo); // Check if we need to fade out the master channel GainCache& gainCache = m_channelMasterGainCache[i]; if (gainCache.m_gain) { gainCache.m_fadeout = true; m_activeBusChannels[pChannel->getOrientation()].append(pChannelInfo); } } else { // Check if we need to fade out the channel GainCache& gainCache = m_channelTalkoverGainCache[i]; if (gainCache.m_gain) { gainCache.m_fadeout = true; m_activeTalkoverChannels.append(pChannelInfo); } if (pChannel->isMasterEnabled() && !pChannelInfo->m_pMuteControl->toBool()) { // the xFader-Mix m_activeBusChannels[pChannel->getOrientation()].append(pChannelInfo); } else { // Check if we need to fade out the channel GainCache& gainCache = m_channelMasterGainCache[i]; if (gainCache.m_gain) { gainCache.m_fadeout = true; m_activeBusChannels[pChannel->getOrientation()].append(pChannelInfo); } } } // If the channel is enabled for previewing in headphones, copy it // over to the headphone buffer if (pChannel->isPflEnabled()) { m_activeHeadphoneChannels.append(pChannelInfo); } else { // Check if we need to fade out the channel GainCache& gainCache = m_channelHeadphoneGainCache[i]; if (gainCache.m_gain) { m_channelHeadphoneGainCache[i].m_fadeout = true; m_activeHeadphoneChannels.append(pChannelInfo); } } // If necessary, add the channel to the list of buffers to process. if (pChannel == pMasterChannel) { // If this is the sync master, it should be processed first. m_activeChannels.replace(0, pChannelInfo); activeChannelsStartIndex = 0; } else { m_activeChannels.append(pChannelInfo); } } // Now that the list is built and ordered, do the processing. for (int i = activeChannelsStartIndex; i < m_activeChannels.size(); ++i) { ChannelInfo* pChannelInfo = m_activeChannels[i]; EngineChannel* pChannel = pChannelInfo->m_pChannel; pChannel->process(pChannelInfo->m_pBuffer, iBufferSize); // Collect metadata for effects if (m_pEngineEffectsManager) { GroupFeatureState features; pChannel->collectFeatures(&features); pChannelInfo->m_features = features; } } // After all the engines have been processed, trigger post-processing // which ensures that all channels are updating certain values at the // same point in time. This prevents sync from failing depending on // if the sync target was processed before or after the sync origin. for (int i = activeChannelsStartIndex; i < m_activeChannels.size(); ++i) {//.........这里部分代码省略.........
开发者ID:DJMaxergy,项目名称:mixxx,代码行数:101,
示例6: mainint main(int argc, char **argv){ string inp = "secrets! very secrets!"; cout << "inp = /"" << inp << "/"" << endl; vector<pt_key32> k = pt_genKey(); pt_expandKey(k); printKey(k); // initialize helib long m=0, p=2, r=1; long L=23; long c=3; long w=64; long d=0; long security = 128; cout << "L=" << L << endl; ZZX G; cout << "Finding m..." << endl; m = FindM(security,L,c,p,d,0,0); cout << "Generating context..." << endl; FHEcontext context(m, p, r); cout << "Building mod-chain..." << endl; buildModChain(context, L, c); cout << "Generating keys..." << endl; FHESecKey seckey(context); const FHEPubKey& pubkey = seckey; G = context.alMod.getFactorsOverZZ()[0]; seckey.GenSecKey(w); addSome1DMatrices(seckey); EncryptedArray ea(context, G); global_nslots = ea.size(); cout << "nslots = " << global_nslots << endl; // set up globals CTvec maxint (ea, pubkey, transpose(uint32ToBits(0xFFFFFFFF))); global_maxint = &maxint; // HEencrypt key timer(true); cout << "Encrypting SIMON key..." << flush; vector<CTvec> encryptedKey = heEncrypt(ea, pubkey, k); timer(); // HEencrypt input cout << "Encrypting inp..." << flush; heblock ct = heEncrypt(ea, pubkey, inp); timer(); cout << "Running protocol..." << endl; for (size_t i = 0; i < T; i++) { cout << "Round " << i+1 << "/" << T << "..." << flush; encRound(encryptedKey[i], ct); timer(); // check intermediate result for noise cout << "decrypting..." << flush; vector<pt_block> bs = heblockToBlocks(seckey, ct); timer(); printf("block0 : 0x%08x 0x%08x/n", bs[0].x, bs[0].y); vector<pt_block> pt_bs = pt_simonEnc(k, inp, i+1); printf("should be : 0x%08x 0x%08x/n", pt_bs[0].x, pt_bs[0].y); cout << "decrypted : /"" << pt_simonDec(k, bs, i+1) << "/" " << endl; } return 0;}
开发者ID:MHBauer,项目名称:helib-demos,代码行数:69,
示例7: StandaloneSetupboolStandaloneSetup(){ timer(0, g_cur_fractal_specific->calctype); return false; // effectively disable solid-guessing}
开发者ID:LegalizeAdulthood,项目名称:iterated-dynamics,代码行数:6,
示例8: powerMethodTestsint powerMethodTests(Epetra_RowMatrix & A, Epetra_RowMatrix & JadA, Epetra_Map & Map, Epetra_Vector & q, Epetra_Vector & z, Epetra_Vector & resid, bool verbose) { // variable needed for iteration double lambda = 0.0; // int niters = 10000; int niters = 300; double tolerance = 1.0e-2; int ierr = 0; ///////////////////////////////////////////////////////////////////////////////////////////////// // Iterate Epetra_Time timer(Map.Comm()); double startTime = timer.ElapsedTime(); EPETRA_TEST_ERR(power_method(false, A, q, z, resid, &lambda, niters, tolerance, verbose),ierr); double elapsed_time = timer.ElapsedTime() - startTime; double total_flops = q.Flops(); double MFLOPs = total_flops/elapsed_time/1000000.0; double lambdaref = lambda; double flopsref = total_flops; if (verbose) cout << "/n/nTotal MFLOPs for reference first solve = " << MFLOPs << endl << "Total FLOPS = " <<total_flops <<endl<<endl; lambda = 0.0; startTime = timer.ElapsedTime(); EPETRA_TEST_ERR(power_method(false, JadA, q, z, resid, &lambda, niters, tolerance, verbose),ierr); elapsed_time = timer.ElapsedTime() - startTime; total_flops = q.Flops(); MFLOPs = total_flops/elapsed_time/1000000.0; if (verbose) cout << "/n/nTotal MFLOPs for candidate first solve = " << MFLOPs << endl << "Total FLOPS = " <<total_flops <<endl<<endl; EPETRA_TEST_ERR(checkValues(lambda,lambdaref," No-transpose Power Method result", verbose),ierr); //EPETRA_TEST_ERR(checkValues(total_flops,flopsref," No-transpose Power Method flop count", verbose),ierr); ///////////////////////////////////////////////////////////////////////////////////////////////// // Solve transpose problem if (verbose) cout << "/n/nUsing transpose of matrix and solving again (should give same result)./n/n" << endl; // Iterate lambda = 0.0; startTime = timer.ElapsedTime(); EPETRA_TEST_ERR(power_method(true, A, q, z, resid, &lambda, niters, tolerance, verbose),ierr); elapsed_time = timer.ElapsedTime() - startTime; total_flops = q.Flops(); MFLOPs = total_flops/elapsed_time/1000000.0; lambdaref = lambda; flopsref = total_flops; if (verbose) cout << "/n/nTotal MFLOPs for reference transpose solve = " << MFLOPs << endl << "Total FLOPS = " <<total_flops <<endl<<endl; lambda = 0.0; startTime = timer.ElapsedTime(); EPETRA_TEST_ERR(power_method(true, JadA, q, z, resid, &lambda, niters, tolerance, verbose),ierr); elapsed_time = timer.ElapsedTime() - startTime; total_flops = q.Flops(); MFLOPs = total_flops/elapsed_time/1000000.0; if (verbose) cout << "/n/nTotal MFLOPs for candidate transpose solve = " << MFLOPs << endl << "Total FLOPS = " <<total_flops <<endl<<endl; EPETRA_TEST_ERR(checkValues(lambda,lambdaref,"Transpose Power Method result", verbose),ierr); //EPETRA_TEST_ERR(checkValues(total_flops,flopsref,"Transpose Power Method flop count", verbose),ierr); EPETRA_TEST_ERR(check(A, JadA, verbose),ierr); return(0);}
开发者ID:haripandey,项目名称:trilinos,代码行数:81,
示例9: v3fvoid ClientLauncher::speed_tests(){ // volatile to avoid some potential compiler optimisations volatile static s16 temp16; volatile static f32 tempf; static v3f tempv3f1; static v3f tempv3f2; static std::string tempstring; static std::string tempstring2; tempv3f1 = v3f(); tempv3f2 = v3f(); tempstring = std::string(); tempstring2 = std::string(); { infostream << "The following test should take around 20ms." << std::endl; TimeTaker timer("Testing std::string speed"); const u32 jj = 10000; for (u32 j = 0; j < jj; j++) { tempstring = ""; tempstring2 = ""; const u32 ii = 10; for (u32 i = 0; i < ii; i++) { tempstring2 += "asd"; } for (u32 i = 0; i < ii+1; i++) { tempstring += "asd"; if (tempstring == tempstring2) break; } } } infostream << "All of the following tests should take around 100ms each." << std::endl; { TimeTaker timer("Testing floating-point conversion speed"); tempf = 0.001; for (u32 i = 0; i < 4000000; i++) { temp16 += tempf; tempf += 0.001; } } { TimeTaker timer("Testing floating-point vector speed"); tempv3f1 = v3f(1, 2, 3); tempv3f2 = v3f(4, 5, 6); for (u32 i = 0; i < 10000000; i++) { tempf += tempv3f1.dotProduct(tempv3f2); tempv3f2 += v3f(7, 8, 9); } } { TimeTaker timer("Testing std::map speed"); std::map<v2s16, f32> map1; tempf = -324; const s16 ii = 300; for (s16 y = 0; y < ii; y++) { for (s16 x = 0; x < ii; x++) { map1[v2s16(x, y)] = tempf; tempf += 1; } } for (s16 y = ii - 1; y >= 0; y--) { for (s16 x = 0; x < ii; x++) { tempf = map1[v2s16(x, y)]; } } } { infostream << "Around 5000/ms should do well here." << std::endl; TimeTaker timer("Testing mutex speed"); Mutex m; u32 n = 0; u32 i = 0; do { n += 10000; for (; i < n; i++) { m.lock(); m.unlock(); } } // Do at least 10ms while(timer.getTimerTime() < 10); u32 dtime = timer.stop(); u32 per_ms = n / dtime; infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl; }}
开发者ID:blockplanet,项目名称:blockplanet,代码行数:98,
示例10: SaveGamevoid SaveGame(const std::string& filename, const ServerSaveGameData& server_save_game_data, const std::vector<PlayerSaveGameData>& player_save_game_data, const Universe& universe, const EmpireManager& empire_manager, const SpeciesManager& species_manager, const CombatLogManager& combat_log_manager, const GalaxySetupData& galaxy_setup_data, bool multiplayer){ ScopedTimer timer("SaveGame: " + filename, true); bool use_binary = GetOptionsDB().Get<bool>("binary-serialization"); DebugLogger() << "SaveGame(" << (use_binary ? "binary" : "zlib-xml") << ") filename: " << filename; GetUniverse().EncodingEmpire() = ALL_EMPIRES; DebugLogger() << "Compiling save empire and preview data"; std::map<int, SaveGameEmpireData> empire_save_game_data = CompileSaveGameEmpireData(empire_manager); SaveGamePreviewData save_preview_data; CompileSaveGamePreviewData(server_save_game_data, player_save_game_data, empire_save_game_data, save_preview_data); // reinterpret save game data as header data for uncompressed header std::vector<PlayerSaveHeaderData> player_save_header_data; for (std::vector<PlayerSaveGameData>::const_iterator it = player_save_game_data.begin(); it != player_save_game_data.end(); ++it) { player_save_header_data.push_back(*it); } try { fs::path path = FilenameToPath(filename); // A relative path should be relative to the save directory. if (path.is_relative()) { path = GetSaveDir() / path; DebugLogger() << "Made save path relative to save dir. Is now: " << path; } if (multiplayer) { // Make sure the path points into our save directory if (!IsInside(path, GetSaveDir())) { path = GetSaveDir() / path.filename(); } } // set up output archive / stream for saving fs::ofstream ofs(path, std::ios_base::binary); if (!ofs) throw std::runtime_error(UNABLE_TO_OPEN_FILE); if (use_binary) { DebugLogger() << "Creating binary oarchive"; freeorion_bin_oarchive boa(ofs); boa << BOOST_SERIALIZATION_NVP(save_preview_data); boa << BOOST_SERIALIZATION_NVP(galaxy_setup_data); boa << BOOST_SERIALIZATION_NVP(server_save_game_data); boa << BOOST_SERIALIZATION_NVP(player_save_header_data); boa << BOOST_SERIALIZATION_NVP(empire_save_game_data); boa << BOOST_SERIALIZATION_NVP(player_save_game_data); boa << BOOST_SERIALIZATION_NVP(empire_manager); boa << BOOST_SERIALIZATION_NVP(species_manager); boa << BOOST_SERIALIZATION_NVP(combat_log_manager); Serialize(boa, universe); DebugLogger() << "Done serializing"; } else { // Two-tier serialization: // main archive is uncompressed serialized header data first // then contains a string for compressed second archive // that contains the main gamestate info // allocate buffers for serialized gamestate DebugLogger() << "Allocating buffers for XML serialization..."; std::string serial_str, compressed_str; try { serial_str.reserve( std::pow(2.0, 29.0)); compressed_str.reserve(std::pow(2.0, 26.0)); } catch (...) { DebugLogger() << "Unable to preallocate full serialization buffers. Attempting serialization with dynamic buffer allocation."; } // wrap buffer string in iostream::stream to receive serialized data typedef boost::iostreams::back_insert_device<std::string> InsertDevice; InsertDevice serial_inserter(serial_str); boost::iostreams::stream<InsertDevice> s_sink(serial_inserter); // create archive with (preallocated) buffer... freeorion_xml_oarchive xoa(s_sink); // serialize main gamestate info xoa << BOOST_SERIALIZATION_NVP(player_save_game_data); xoa << BOOST_SERIALIZATION_NVP(empire_manager); xoa << BOOST_SERIALIZATION_NVP(species_manager); xoa << BOOST_SERIALIZATION_NVP(combat_log_manager); Serialize(xoa, universe); s_sink.flush(); // wrap gamestate string in iostream::stream to extract serialized data typedef boost::iostreams::basic_array_source<char> SourceDevice; SourceDevice source(serial_str.data(), serial_str.size()); boost::iostreams::stream<SourceDevice> s_source(source); // wrap compresed buffer string in iostream::streams to receive compressed string InsertDevice compressed_inserter(compressed_str);//.........这里部分代码省略.........
开发者ID:Blue42hand,项目名称:freeorion,代码行数:101,
示例11: LoadGamevoid LoadGame(const std::string& filename, ServerSaveGameData& server_save_game_data, std::vector<PlayerSaveGameData>& player_save_game_data, Universe& universe, EmpireManager& empire_manager, SpeciesManager& species_manager, CombatLogManager& combat_log_manager, GalaxySetupData& galaxy_setup_data){ //boost::this_thread::sleep_for(boost::chrono::seconds(1)); ScopedTimer timer("LoadGame: " + filename, true); // player notifications if (ServerApp* server = ServerApp::GetApp()) server->Networking().SendMessage(TurnProgressMessage(Message::LOADING_GAME)); GetUniverse().EncodingEmpire() = ALL_EMPIRES; std::map<int, SaveGameEmpireData> ignored_save_game_empire_data; SaveGamePreviewData ignored_save_preview_data; std::vector<PlayerSaveHeaderData> ignored_player_save_header_data; empire_manager.Clear(); universe.Clear(); try { // set up input archive / stream for loading const fs::path path = FilenameToPath(filename); fs::ifstream ifs(path, std::ios_base::binary); if (!ifs) throw std::runtime_error(UNABLE_TO_OPEN_FILE); try { // first attempt binary deserialziation freeorion_bin_iarchive ia(ifs); DebugLogger() << "Reading binary iarchive"; ia >> BOOST_SERIALIZATION_NVP(ignored_save_preview_data); ia >> BOOST_SERIALIZATION_NVP(galaxy_setup_data); ia >> BOOST_SERIALIZATION_NVP(server_save_game_data); ia >> BOOST_SERIALIZATION_NVP(ignored_player_save_header_data); ia >> BOOST_SERIALIZATION_NVP(ignored_save_game_empire_data); ia >> BOOST_SERIALIZATION_NVP(player_save_game_data); ia >> BOOST_SERIALIZATION_NVP(empire_manager); ia >> BOOST_SERIALIZATION_NVP(species_manager); ia >> BOOST_SERIALIZATION_NVP(combat_log_manager); Deserialize(ia, universe); DebugLogger() << "Done deserializing"; } catch (...) { // if binary deserialization failed, try more-portable XML deserialization // reset to start of stream (attempted binary serialization will have consumed some input...) boost::iostreams::seek(ifs, 0, std::ios_base::beg); // allocate buffers for serialized gamestate DebugLogger() << "Allocating buffers for XML deserialization..."; std::string serial_str, compressed_str; try { serial_str.reserve( std::pow(2.0, 29.0)); compressed_str.reserve(std::pow(2.0, 26.0)); } catch (...) { DebugLogger() << "Unable to preallocate full deserialization buffers. Attempting deserialization with dynamic buffer allocation."; } // create archive with (preallocated) buffer... freeorion_xml_iarchive xia(ifs); // read from save file: uncompressed header serialized data, with compressed main archive string at end... // deserialize uncompressed save header info xia >> BOOST_SERIALIZATION_NVP(ignored_save_preview_data); xia >> BOOST_SERIALIZATION_NVP(galaxy_setup_data); xia >> BOOST_SERIALIZATION_NVP(server_save_game_data); xia >> BOOST_SERIALIZATION_NVP(ignored_player_save_header_data); xia >> BOOST_SERIALIZATION_NVP(ignored_save_game_empire_data); // extract compressed gamestate info xia >> BOOST_SERIALIZATION_NVP(compressed_str); // wrap compressed string in iostream::stream to extract compressed data typedef boost::iostreams::basic_array_source<char> SourceDevice; SourceDevice compressed_source(compressed_str.data(), compressed_str.size()); boost::iostreams::stream<SourceDevice> c_source(compressed_source); // wrap uncompressed buffer string in iostream::stream to receive decompressed string typedef boost::iostreams::back_insert_device<std::string> InsertDevice; InsertDevice serial_inserter(serial_str); boost::iostreams::stream<InsertDevice> s_sink(serial_inserter); // set up filter to decompress data boost::iostreams::filtering_istreambuf i; i.push(boost::iostreams::zlib_decompressor()); i.push(c_source); boost::iostreams::copy(i, s_sink); // The following line has been commented out because it caused an assertion in boost iostreams to fail // s_sink.flush(); // wrap uncompressed buffer string in iostream::stream to extract decompressed string SourceDevice serial_source(serial_str.data(), serial_str.size()); boost::iostreams::stream<SourceDevice> s_source(serial_source); // create archive with (preallocated) buffer... freeorion_xml_iarchive xia2(s_source); // deserialize main gamestate info xia2 >> BOOST_SERIALIZATION_NVP(player_save_game_data); xia2 >> BOOST_SERIALIZATION_NVP(empire_manager);//.........这里部分代码省略.........
开发者ID:Blue42hand,项目名称:freeorion,代码行数:101,
示例12: main// ######################################################################int main(const int argc, const char **argv){ MYLOGVERB = LOG_INFO; // suppress debug messages // instantiate a model manager: ModelManager manager("Test Optic Flow"); nub::ref<InputFrameSeries> ifs(new InputFrameSeries(manager)); manager.addSubComponent(ifs); nub::ref<OutputFrameSeries> ofs(new OutputFrameSeries(manager)); manager.addSubComponent(ofs); //nub::ref<PopulationHeadingMap> phm(new PopulationHeadingMap(manager)); rutz::shared_ptr<PopulationHeadingMap> phm(new PopulationHeadingMap(400.0)); manager.exportOptions(MC_RECURSE); if (manager.parseCommandLine((const int)argc, (const char**)argv, "", 0, 0) == false) return(1); // get some options // if(manager.numExtraArgs() > 0) // { // outFilename = manager.getExtraArg(0); // LINFO("save to: %s", outFilename.c_str()); // } // let's do it! manager.start(); Timer timer(1000000); timer.reset(); // reset the timer int frame = 0; bool keepGoing = true; const FrameState is = ifs->updateNext(); ifs->updateNext(); Image<PixRGB<byte> > img1 = ifs->readRGB(); ifs->updateNext(); Image<PixRGB<byte> > img2 = ifs->readRGB(); Image<PixRGB<byte> > image; Image<float> stim; if (is == FRAME_COMPLETE) keepGoing = false; float flen = 400; while (keepGoing) { if (ofs->becameVoid()) { LINFO("quitting because output stream was closed or became void"); break; } // get the frame const FrameState is = ifs->updateNext(); if (is == FRAME_COMPLETE) break; // done receiving frames image = ifs->readRGB(); // compute the Focus of Expansion phm->setFocalLength(flen); //flen += 5.0; phm->getFOE(Image<byte>(luminance(img1)),Image<byte>(luminance(img2))); //phm->getFOE(Image<byte>(luminance(image))); ofs->writeRGB(image, "Optic Flow"); const FrameState os = ofs->updateNext(); Raster::waitForKey(); //Raster::WriteRGB(currImage, sformat("image%d.ppm",frame)); if (os == FRAME_FINAL) break; frame++; } // stop all our ModelComponents manager.stop(); // all done! return 0;}
开发者ID:ulyssesrr,项目名称:carmen_lcad,代码行数:83,
示例13: gl_drawvoid gl_draw( void ){ int i, j; GLfloat len, lmax, r[8], g[8], b[8], a; glClear( GL_COLOR_BUFFER_BIT ); for( i = 0; i < 8; i++ ) { for( j = 0; j < 3; j++ ) { if( fps ) { if( ! ( rand() % (int) ( fps * 16.0f ) ) ) { dir[i][j] = (GLfloat) ( rand() % 3 ) - 1; } phi[i][j] += dir[i][j] / fps; } } } for( i = 0; i < 8; i++ ) { r[i] = ( (GLfloat) sin( phi[i][0] ) + 1.0f ) / 2.0f; g[i] = ( (GLfloat) sin( phi[i][1] ) + 1.0f ) / 2.0f; b[i] = ( (GLfloat) sin( phi[i][2] ) + 1.0f ) / 2.0f; } if( fps ) { rx += vx / fps; ry += vy / fps; } glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glTranslatef( 0.0f, 0.0f, -8.0f ); glRotatef( rx, 1.0f, 0.0f, 0.0f ); glRotatef( ry, 0.0f, 1.0f, 0.0f ); a = alpha; lmax = 1.4f + 0.12f * bmode; glBegin( GL_QUADS ); for( len = lmax; len > 0.0f; len -= 0.12f ) { glColor4f( r[0], g[0], b[0], a ); glVertex3f( -len, -len, -len ); glColor4f( r[1], g[1], b[1], a ); glVertex3f( -len, -len, len ); glColor4f( r[2], g[2], b[2], a ); glVertex3f( -len, len, len ); glColor4f( r[3], g[3], b[3], a ); glVertex3f( -len, len, -len ); glColor4f( r[4], g[4], b[4], a ); glVertex3f( len, -len, -len ); glColor4f( r[5], g[5], b[5], a ); glVertex3f( len, -len, len ); glColor4f( r[6], g[6], b[6], a ); glVertex3f( len, len, len ); glColor4f( r[7], g[7], b[7], a ); glVertex3f( len, len, -len ); glColor4f( r[0], g[0], b[0], a ); glVertex3f( -len, -len, -len ); glColor4f( r[1], g[1], b[1], a ); glVertex3f( -len, -len, len ); glColor4f( r[5], g[5], b[5], a ); glVertex3f( len, -len, len ); glColor4f( r[4], g[4], b[4], a ); glVertex3f( len, -len, -len ); glColor4f( r[3], g[3], b[3], a ); glVertex3f( -len, len, -len ); glColor4f( r[2], g[2], b[2], a ); glVertex3f( -len, len, len ); glColor4f( r[6], g[6], b[6], a ); glVertex3f( len, len, len ); glColor4f( r[7], g[7], b[7], a ); glVertex3f( len, len, -len ); glColor4f( r[0], g[0], b[0], a ); glVertex3f( -len, -len, -len ); glColor4f( r[3], g[3], b[3], a ); glVertex3f( -len, len, -len ); glColor4f( r[7], g[7], b[7], a ); glVertex3f( len, len, -len ); glColor4f( r[4], g[4], b[4], a ); glVertex3f( len, -len, -len ); glColor4f( r[1], g[1], b[1], a ); glVertex3f( -len, -len, len ); glColor4f( r[2], g[2], b[2], a ); glVertex3f( -len, len, len ); glColor4f( r[6], g[6], b[6], a ); glVertex3f( len, len, len ); glColor4f( r[5], g[5], b[5], a ); glVertex3f( len, -len, len ); } glEnd(); if( fps && info ) { gl_printf( 0.7f, 0.7f, 0.7f, 1.0f, width - 114, height - 40, font, "%5.1f fps", fps ); } glFinish(); frames++; if( timer( &tv, 0 ) >= 0.2f ) { fps = (GLfloat) frames / timer( &tv, 1 ); frames = 0; }}
开发者ID:cjxgm,项目名称:clabs,代码行数:100,
示例14: emitAllHHBC/* * This is the entry point for offline bytecode generation. */void emitAllHHBC(AnalysisResultPtr&& ar) { auto ues = ar->getHhasFiles(); decltype(ues) ues_to_print; auto const outputPath = ar->getOutputPath(); std::thread wp_thread; auto unexpectedException = [&] (const char* what) { if (wp_thread.joinable()) { Logger::Error("emitAllHHBC exited via an exception " "before wp_thread was joined: %s", what); } throw; }; try { { SCOPE_EXIT { genText(ues_to_print, outputPath); }; auto commitSome = [&] (decltype(ues)& emitters) { batchCommit(emitters); if (Option::GenerateTextHHBC || Option::GenerateHhasHHBC) { std::move(emitters.begin(), emitters.end(), std::back_inserter(ues_to_print)); } emitters.clear(); }; if (!RuntimeOption::EvalUseHHBBC && ues.size()) { commitSome(ues); } HHBBC::UnitEmitterQueue ueq; auto commitLoop = [&] { folly::Optional<Timer> commitTime; // kBatchSize needs to strike a balance between reducing // transaction commit overhead (bigger batches are better), and // limiting the cost incurred by failed commits due to identical // units that require rollback and retry (smaller batches have // less to lose). Empirical results indicate that a value in // the 2-10 range is reasonable. static const unsigned kBatchSize = 8; while (auto ue = ueq.pop()) { if (!commitTime) { commitTime.emplace(Timer::WallTime, "committing units to repo"); } ues.push_back(std::move(ue)); if (ues.size() == kBatchSize) { commitSome(ues); } } if (ues.size()) commitSome(ues); }; LitstrTable::get().setReading(); ar->finish(); ar.reset(); if (!RuntimeOption::EvalUseHHBBC) { if (Option::GenerateBinaryHHBC) { commitGlobalData(std::unique_ptr<ArrayTypeTable::Builder>{}); } return; } RuntimeOption::EvalJit = false; // For HHBBC to invoke builtins. std::unique_ptr<ArrayTypeTable::Builder> arrTable; wp_thread = std::thread([&] { Timer timer(Timer::WallTime, "running HHBBC"); hphp_thread_init(); hphp_session_init(Treadmill::SessionKind::CompilerEmit); SCOPE_EXIT { hphp_context_exit(); hphp_session_exit(); hphp_thread_exit(); }; HHBBC::whole_program( std::move(ues), ueq, arrTable, Option::ParserThreadCount > 0 ? Option::ParserThreadCount : 0); }); commitLoop(); LitstrTable::get().setReading(); commitGlobalData(std::move(arrTable)); } wp_thread.join(); } catch (std::exception& ex) {
开发者ID:facebook,项目名称:hhvm,代码行数:96,
示例15: WinMain //-----------------------------------WinMain----------------------------------------- // Entry point for our windows application //-----------------------------------------------------------------------------------int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline, int ncmdshow){ WNDCLASSEX winclass; HWND hwnd; MSG msg; // first fill in the window class stucture winclass.cbSize = sizeof(WNDCLASSEX); winclass.style = CS_HREDRAW | CS_VREDRAW; winclass.lpfnWndProc = WindowProc; winclass.cbClsExtra = 0; winclass.cbWndExtra = 0; winclass.hInstance = hinstance; winclass.hIcon = LoadIcon(hinstance, MAKEINTRESOURCE(IDI_ICON1)); winclass.hCursor = LoadCursor(NULL, IDC_ARROW); winclass.hbrBackground = NULL; winclass.lpszMenuName = NULL; winclass.lpszClassName = szWindowClassName; winclass.hIconSm = LoadIcon(hinstance, MAKEINTRESOURCE(IDI_ICON1)); // register the window class if (!RegisterClassEx(&winclass)) { MessageBox(NULL, "Error Registering Class!", "Error", 0); return 0; } // create the window (one that cannot be resized) if (!(hwnd = CreateWindowEx(NULL, szWindowClassName, szApplicationName, WS_OVERLAPPED | WS_VISIBLE | WS_CAPTION | WS_SYSMENU, GetSystemMetrics(SM_CXSCREEN) / 2 - CParams::WindowWidth / 2, GetSystemMetrics(SM_CYSCREEN) / 2 - CParams::WindowHeight / 2, CParams::WindowWidth, CParams::WindowHeight, NULL, NULL, hinstance, NULL))) { MessageBox(NULL, "Error Creating Window!", "Error", 0); return 0; } //Show the window ShowWindow(hwnd, SW_SHOWDEFAULT); UpdateWindow(hwnd); //create a timer CTimer timer(CParams::iFramesPerSecond); //start the timer timer.Start(); globalTimer_p = &timer; // Enter the message loop bool bDone = FALSE; while (!bDone) { while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) { //Stop loop if it's a quit message bDone = TRUE; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } if (timer.ReadyForNextFrame() || g_pController->FastRender()) { if (!g_pController->Update()) { //we have a problem, end app bDone = TRUE; } //this will call WM_PAINT which will render our scene InvalidateRect(hwnd, NULL, TRUE); UpdateWindow(hwnd); }//.........这里部分代码省略.........
开发者ID:craigaloewen,项目名称:FlappyBirdAI,代码行数:101,
示例16: model//.........这里部分代码省略......... model.add(c[u] - c[v] + M * (z0[i]) >= Par_d[u][v]); model.add(c[v] - c[u] + M * (1 - z0[i]) >= Par_d[u][v]); } */ for (unsigned u=0; u<n; u++) { for (unsigned v=0; v<u; v++) { if (Par_d[u][v] <= max_distance) { model.add(c[v]-c[u]+M*z0[u][v] >=Par_d[u][v]); model.add(c[u]-c[v]+M*(1-z0[u][v]) >=Par_d[u][v]); //Info.numvar++; } } } // d(x) = 3 - x if (max_distance == 2) { // Sechsecke mit der Seitenlaenge 1 model.add(c[0]+c[2] +c[3] +c[5] +c[6] +c[9]>=16.6077); model.add(c[1]+c[3] +c[4] +c[6] +c[7] +c[10]>=16.6077); model.add(c[5]+c[8] +c[9] +c[12]+c[13]+c[16]>=16.6077); model.add(c[6]+c[9] +c[10]+c[13]+c[14]+c[17]>=16.6077); model.add(c[7]+c[10]+c[11]+c[14]+c[15]+c[18]>=16.6077); model.add(c[13]+c[16]+c[17]+c[19]+c[20]+c[22]>=16.6077); model.add(c[14]+c[17]+c[18]+c[20]+c[21]+c[23]>=16.6077); } //d(x) = 4 - x if (max_distance == 3) { // Sechsecke mit der Seitenlaenge 1 model.add(c[0]+c[2] +c[3] +c[5] +c[6] +c[9]>=31.6077); model.add(c[1]+c[3] +c[4] +c[6] +c[7] +c[10]>=31.6077); model.add(c[5]+c[8] +c[9] +c[12]+c[13]+c[16]>=31.6077); model.add(c[6]+c[9] +c[10]+c[13]+c[14]+c[17]>=31.6077); model.add(c[7]+c[10]+c[11]+c[14]+c[15]+c[18]>=31.6077); model.add(c[13]+c[16]+c[17]+c[19]+c[20]+c[22]>=31.6077); model.add(c[14]+c[17]+c[18]+c[20]+c[21]+c[23]>=31.6077); } for (unsigned int v = 0; v < n; v++) { model.add(c[v] <= lambda); model.add(c[v] >= 0); } std::cout << "Number of variables " << Info.numVar << "/n"; /* solve the Model*/ cplex.extract(model); cplex.exportModel("L-Labeling.lp"); cplex.setParam(IloCplex::ClockType,1); IloTimer timer(env); timer.start(); int solveError = cplex.solve(); timer.stop(); if (!solveError) { std::cout << "STATUS : " << cplex.getStatus() << "/n"; env.error() << "Failed to optimize LP /n"; exit(1); } //Info.time = (double)(end-start)/(double)CLOCKS_PER_SEC; Info.time = timer.getTime(); std::cout << "STATUS : " << cplex.getStatus() << "/n"; /* get the solution*/ env.out() << "Solution status = " << cplex.getStatus() << "/n"; Info.numConstr = cplex.getNrows(); env.out() << " Number of constraints = " << Info.numConstr << "/n"; lambda_G_d = cplex.getObjValue(); env.out() << "Solution value = " << lambda_G_d << "/n"; for (unsigned int u = 0; u < n; u++) { C.push_back(cplex.getValue(c[u])); std::cout << "c(" << u << ")=" << C[u] << " "; } } // end try catch (IloException& e) { std::cerr << "Concert exception caught: " << e << std::endl; } catch (...) { std::cerr << "Unknown exception caught" << std::endl; } env.end(); return 0;}
开发者ID:tikhoncheva,项目名称:work,代码行数:101,
示例17: mainint main(int argc, char** argv){ /* variable declaration */ DB(DB_LVL, "declaration"); DT * memA_t0, *memA_t1, *memA_t2, *memA_t3; DT * memB_t0, *memB_t1, *memB_t2, *memB_t3; int reps, size; int samples; int tid; int i, p, r, bytes, elems; int bytes_min, bytes_max; int elems_min, elems_max; double func_overhead; double t_start, t_end; double t_min, c_min; double alpha = 0.5; DB(DB_LVL, SEPERATOR); /* initialization */ DB(DB_LVL, "intialization"); samples = 3; bytes_min = 1024, bytes_max = 1024*32; /* [1KB, 32KB] */ elems_min = bytes_min/sizeof(DT), elems_max = bytes_max/sizeof(DT); /* the number of elements */ reps = 40000; DB(DB_LVL, SEPERATOR); /* omp environment */ const int nthreads = argc > 1 ? atoi(argv[1]) : 4; fprintf(stderr , "nthreads= %d/n", nthreads); omp_set_num_threads(nthreads); /* iteration */ DB(DB_LVL, "measurement"); for(elems=elems_min, bytes=bytes_min; elems<=elems_max; elems=elems+elems_min, bytes=bytes+bytes_min) { memA_t0 = (DT *)_mm_malloc(bytes_max, 64); memA_t1 = (DT *)_mm_malloc(bytes_max, 64); memA_t2 = (DT *)_mm_malloc(bytes_max, 64); memA_t3 = (DT *)_mm_malloc(bytes_max, 64); memB_t0 = (DT *)_mm_malloc(bytes_max, 64); memB_t1 = (DT *)_mm_malloc(bytes_max, 64); memB_t2 = (DT *)_mm_malloc(bytes_max, 64); memB_t3 = (DT *)_mm_malloc(bytes_max, 64); /* initialization a local space */ fill(memA_t0, elems, 1.0); fill(memA_t1, elems, 2.0); fill(memA_t2, elems, 3.0); fill(memA_t3, elems, 4.0); fill(memB_t0, elems, 1.0); fill(memB_t1, elems, 2.0); fill(memB_t2, elems, 3.0); fill(memB_t3, elems, 4.0); /* measurement */ t_min = 0.0f; c_min = 0.0f; DT ret_t0 = 0.0; DT ret_t1 = 0.0; DT ret_t2 = 0.0; DT ret_t3 = 0.0;#ifdef SAXPY2#define Z _y#else#define Z _y#endif for(p=0; p<samples; p++) { __m512d *_x, *_y, *_z; #pragma omp parallel private(_x,_y,_z) default(shared) { int tid; tid = omp_get_thread_num(); switch(tid) { case 0: _x = (__m512d*)memA_t0; _y = (__m512d*)memB_t0; break; case 1: _x = (__m512d*)memA_t1; _y = (__m512d*)memB_t1; break; case 2: _x = (__m512d*)memA_t2; _y = (__m512d*)memB_t2; break; case 3: _x = (__m512d*)memA_t3; _y = (__m512d*)memB_t3; break; default: assert(0); }#pragma omp barrier if(p==(samples-1)) t_start = timer(); //.........这里部分代码省略.........
开发者ID:haibo031031,项目名称:mic-meter,代码行数:101,
示例18: GDEBUG//.........这里部分代码省略......... ((static_cast<unsigned int>(std::ceil(matrix_size_[1]*oversampling_factor_))+warp_size-1)/warp_size)*warp_size); GDEBUG("Matrix size : [%d,%d] /n", matrix_size_[0], matrix_size_[1]); GDEBUG("Matrix size OS : [%d,%d] /n", matrix_size_os_[0], matrix_size_os_[1]); std::vector<size_t> image_dims = to_std_vector(matrix_size_); image_dims.push_back(frames); E_->set_domain_dimensions(&image_dims); E_->set_codomain_dimensions(device_samples->get_dimensions().get()); E_->set_csm(csm); E_->setup( matrix_size_, matrix_size_os_, kernel_width_ ); E_->preprocess(traj.get()); { auto precon = boost::make_shared<cuNDArray<float_complext>>(image_dims); fill(precon.get(),float_complext(1.0f)); //solver_.set_preconditioning_image(precon); } reg_image_ = boost::shared_ptr< cuNDArray<float_complext> >(new cuNDArray<float_complext>(&image_dims)); // These operators need their domain/codomain set before being added to the solver // //E_->set_dcw(dcw); GDEBUG("Prepared/n"); // Expand the average image to the number of frames // { cuNDArray<float_complext> tmp(*j->reg_host_); *reg_image_ = expand( tmp, frames ); } PICS_->set_prior(reg_image_); // Define preconditioning weights // //Apply weights //*device_samples *= *dcw; // Invoke solver // boost::shared_ptr< cuNDArray<float_complext> > result; { GDEBUG("Running NLCG solver/n"); GPUTimer timer("Running NLCG solver"); // Optionally, allow exclusive (per device) access to the solver // This may not matter much in terms of speed, but it can in terms of memory consumption // if( exclusive_access_ ) _mutex[device_number_].lock(); result = solver_.solve(device_samples.get()); if( exclusive_access_ ) _mutex[device_number_].unlock(); } // Provide some info about the scaling between the regularization and reconstruction. // If it is not close to one, PICCS does not work optimally... // if( alpha_ > 0.0 ){ cuNDArray<float_complext> gpureg(j->reg_host_.get()); boost::shared_ptr< cuNDArray<float_complext> > gpurec = sum(result.get(),2); *gpurec /= float(result->get_size(2)); float scale = abs(dot(gpurec.get(), gpurec.get())/dot(gpurec.get(),&gpureg)); GDEBUG("Scaling factor between regularization and reconstruction is %f./n", scale); } if (!result.get()) { GDEBUG("/nNon-linear conjugate gradient solver failed/n"); return GADGET_FAIL; } /* static int counter = 0; char filename[256]; sprintf((char*)filename, "recon_sb_%d.cplx", counter); write_nd_array<float_complext>( sbresult->to_host().get(), filename ); counter++; */ // If the recon matrix size exceeds the sequence matrix size then crop if( matrix_size_seq_ != matrix_size_ ) *result = crop<float_complext,2>( (matrix_size_-matrix_size_seq_)>>1, matrix_size_seq_, *result ); // Now pass on the reconstructed images // this->put_frames_on_que(frames,rotations,j,result.get(),channels); frame_counter_ += frames; m1->release(); return GADGET_OK;}
开发者ID:congzhangzh,项目名称:gadgetron,代码行数:101,
示例19: timerint HttpClient::impl(const char *url, const char *data, int size, StringBuffer &response, const HeaderMap *requestHeaders, std::vector<String> *responseHeaders) { SlowTimer timer(RuntimeOption::HttpSlowQueryThreshold, "curl", url); m_response = &response; char error_str[CURL_ERROR_SIZE + 1]; memset(error_str, 0, sizeof(error_str)); CURL *cp = curl_easy_init(); curl_easy_setopt(cp, CURLOPT_URL, url); curl_easy_setopt(cp, CURLOPT_WRITEFUNCTION, curl_write); curl_easy_setopt(cp, CURLOPT_WRITEDATA, (void*)this); curl_easy_setopt(cp, CURLOPT_ERRORBUFFER, error_str); curl_easy_setopt(cp, CURLOPT_NOPROGRESS, 1); curl_easy_setopt(cp, CURLOPT_VERBOSE, 0); curl_easy_setopt(cp, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(cp, CURLOPT_DNS_USE_GLOBAL_CACHE, 0); // for thread-safe curl_easy_setopt(cp, CURLOPT_DNS_CACHE_TIMEOUT, 120); curl_easy_setopt(cp, CURLOPT_NOSIGNAL, 1); // for multithreading mode curl_easy_setopt(cp, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(cp, CURLOPT_SSL_CTX_FUNCTION, curl_tls_workarounds_cb); curl_easy_setopt(cp, CURLOPT_TIMEOUT, m_timeout); if (m_maxRedirect > 1) { curl_easy_setopt(cp, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(cp, CURLOPT_MAXREDIRS, m_maxRedirect); } else { curl_easy_setopt(cp, CURLOPT_FOLLOWLOCATION, 0); } if (!m_use11) { curl_easy_setopt(cp, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); } if (m_decompress) { curl_easy_setopt(cp, CURLOPT_ENCODING, ""); } if (!m_username.empty()) { curl_easy_setopt(cp, CURLOPT_HTTPAUTH, m_basic ? CURLAUTH_BASIC : CURLAUTH_DIGEST); curl_easy_setopt(cp, CURLOPT_USERNAME, m_username.c_str()); curl_easy_setopt(cp, CURLOPT_PASSWORD, m_password.c_str()); } if (!m_proxyHost.empty() && m_proxyPort) { curl_easy_setopt(cp, CURLOPT_PROXY, m_proxyHost.c_str()); curl_easy_setopt(cp, CURLOPT_PROXYPORT, m_proxyPort); if (!m_proxyUsername.empty()) { curl_easy_setopt(cp, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); curl_easy_setopt(cp, CURLOPT_PROXYUSERNAME, m_proxyUsername.c_str()); curl_easy_setopt(cp, CURLOPT_PROXYPASSWORD, m_proxyPassword.c_str()); } } std::vector<String> headers; // holding those temporary strings curl_slist *slist = nullptr; if (requestHeaders) { for (HeaderMap::const_iterator iter = requestHeaders->begin(); iter != requestHeaders->end(); ++iter) { for (unsigned int i = 0; i < iter->second.size(); i++) { String header = iter->first + ": " + iter->second[i]; headers.push_back(header); slist = curl_slist_append(slist, header.data()); } } if (slist) { curl_easy_setopt(cp, CURLOPT_HTTPHEADER, slist); } } if (data && size) { curl_easy_setopt(cp, CURLOPT_POST, 1); curl_easy_setopt(cp, CURLOPT_POSTFIELDS, data); curl_easy_setopt(cp, CURLOPT_POSTFIELDSIZE, size); } if (responseHeaders) { m_responseHeaders = responseHeaders; curl_easy_setopt(cp, CURLOPT_HEADERFUNCTION, curl_header); curl_easy_setopt(cp, CURLOPT_WRITEHEADER, (void*)this); } if (m_stream_context_options[s_ssl].isArray()) { const Array ssl = m_stream_context_options[s_ssl].toArray(); if (ssl[s_verify_peer].toBoolean()) { curl_easy_setopt(cp, CURLOPT_SSL_VERIFYPEER, 1); } if (ssl.exists(s_capath)) { curl_easy_setopt(cp, CURLOPT_CAPATH, ssl[s_capath].toString().data()); } if (ssl.exists(s_cafile)) { curl_easy_setopt(cp, CURLOPT_CAINFO, ssl[s_cafile].toString().data()); } if (ssl.exists(s_local_cert)) { curl_easy_setopt(cp, CURLOPT_SSLKEY, ssl[s_local_cert].toString().data()); curl_easy_setopt(cp, CURLOPT_SSLKEYTYPE, "PEM");//.........这里部分代码省略.........
开发者ID:MrLunar,项目名称:hiphop-php,代码行数:101,
示例20: ifStatusWith<bool> ReplSetDistLockManager::canOvertakeLock(OperationContext* txn, LocksType lockDoc, const milliseconds& lockExpiration) { const auto& processID = lockDoc.getProcess(); auto pingStatus = _catalog->getPing(txn, processID); Date_t pingValue; if (pingStatus.isOK()) { const auto& pingDoc = pingStatus.getValue(); Status pingDocValidationStatus = pingDoc.validate(); if (!pingDocValidationStatus.isOK()) { return {ErrorCodes::UnsupportedFormat, str::stream() << "invalid ping document for " << processID << ": " << pingDocValidationStatus.toString()}; } pingValue = pingDoc.getPing(); } else if (pingStatus.getStatus() != ErrorCodes::NoMatchingDocument) { return pingStatus.getStatus(); } // else use default pingValue if ping document does not exist. Timer timer(_serviceContext->getTickSource()); auto serverInfoStatus = _catalog->getServerInfo(txn); if (!serverInfoStatus.isOK()) { return serverInfoStatus.getStatus(); } // Be conservative when determining that lock expiration has elapsed by // taking into account the roundtrip delay of trying to get the local // time from the config server. milliseconds delay(timer.millis() / 2); // Assuming symmetrical delay. const auto& serverInfo = serverInfoStatus.getValue(); stdx::lock_guard<stdx::mutex> lk(_mutex); auto pingIter = _pingHistory.find(lockDoc.getName()); if (pingIter == _pingHistory.end()) { // We haven't seen this lock before so we don't have any point of reference // to compare and determine the elapsed time. Save the current ping info // for this lock. _pingHistory.emplace(std::piecewise_construct, std::forward_as_tuple(lockDoc.getName()), std::forward_as_tuple(processID, pingValue, serverInfo.serverTime, lockDoc.getLockID(), serverInfo.electionId)); return false; } auto configServerLocalTime = serverInfo.serverTime - delay; auto* pingInfo = &pingIter->second; LOG(1) << "checking last ping for lock '" << lockDoc.getName() << "' against last seen process " << pingInfo->processId << " and ping " << pingInfo->lastPing; if (pingInfo->lastPing != pingValue || // ping is active // Owner of this lock is now different from last time so we can't // use the ping data. pingInfo->lockSessionId != lockDoc.getLockID() || // Primary changed, we can't trust that clocks are synchronized so // treat as if this is a new entry. pingInfo->electionId != serverInfo.electionId) { pingInfo->lastPing = pingValue; pingInfo->electionId = serverInfo.electionId; pingInfo->configLocalTime = configServerLocalTime; pingInfo->lockSessionId = lockDoc.getLockID(); return false; } if (configServerLocalTime < pingInfo->configLocalTime) { warning() << "config server local time went backwards, from last seen: " << pingInfo->configLocalTime << " to " << configServerLocalTime; return false; } milliseconds elapsedSinceLastPing(configServerLocalTime - pingInfo->configLocalTime); if (elapsedSinceLastPing >= lockExpiration) { LOG(0) << "forcing lock '" << lockDoc.getName() << "' because elapsed time " << elapsedSinceLastPing << " >= takeover time " << lockExpiration; return true; } LOG(1) << "could not force lock '" << lockDoc.getName() << "' because elapsed time " << durationCount<Milliseconds>(elapsedSinceLastPing) << " < takeover time " << durationCount<Milliseconds>(lockExpiration) << " ms"; return false;}
开发者ID:dingzhengkai,项目名称:robomongo-shell,代码行数:92,
示例21: hisat2_build//.........这里部分代码省略......... printUsage(cerr); return 1; } outfile = argv[optind++]; tokenize(infile, ",", infiles); if(infiles.size() < 1) { cerr << "Tokenized input file list was empty!" << endl; printUsage(cerr); return 1; } if(!lineRate_provided) { if(snp_fname == "" && ss_fname == "" && exon_fname == "") { lineRate = GFM<TIndexOffU>::default_lineRate_fm; } else { lineRate = GFM<TIndexOffU>::default_lineRate_gfm; } } // Optionally summarize if(verbose) { cerr << "Settings:" << endl << " Output files: /"" << outfile.c_str() << ".*." << gfm_ext << "/"" << endl << " Line rate: " << lineRate << " (line is " << (1<<lineRate) << " bytes)" << endl << " Lines per side: " << linesPerSide << " (side is " << ((1<<lineRate)*linesPerSide) << " bytes)" << endl << " Offset rate: " << offRate << " (one in " << (1<<offRate) << ")" << endl << " FTable chars: " << ftabChars << endl << " Strings: " << (packed? "packed" : "unpacked") << endl << " Local offset rate: " << localOffRate << " (one in " << (1<<localOffRate) << ")" << endl << " Local fTable chars: " << localFtabChars << endl << " Local sequence length: " << local_index_size << endl << " Local sequence overlap between two consecutive indexes: " << local_index_overlap << endl;#if 0 if(bmax == OFF_MASK) { cerr << " Max bucket size: default" << endl; } else { cerr << " Max bucket size: " << bmax << endl; } if(bmaxMultSqrt == OFF_MASK) { cerr << " Max bucket size, sqrt multiplier: default" << endl; } else { cerr << " Max bucket size, sqrt multiplier: " << bmaxMultSqrt << endl; } if(bmaxDivN == 0xffffffff) { cerr << " Max bucket size, len divisor: default" << endl; } else { cerr << " Max bucket size, len divisor: " << bmaxDivN << endl; } cerr << " Difference-cover sample period: " << dcv << endl;#endif cerr << " Endianness: " << (bigEndian? "big":"little") << endl << " Actual local endianness: " << (currentlyBigEndian()? "big":"little") << endl << " Sanity checking: " << (sanityCheck? "enabled":"disabled") << endl; #ifdef NDEBUG cerr << " Assertions: disabled" << endl; #else cerr << " Assertions: enabled" << endl; #endif cerr << " Random seed: " << seed << endl; cerr << " Sizeofs: void*:" << sizeof(void*) << ", int:" << sizeof(int) << ", long:" << sizeof(long) << ", size_t:" << sizeof(size_t) << endl; cerr << "Input files DNA, " << file_format_names[format].c_str() << ":" << endl; for(size_t i = 0; i < infiles.size(); i++) { cerr << " " << infiles[i].c_str() << endl; } } // Seed random number generator srand(seed); { Timer timer(cerr, "Total time for call to driver() for forward index: ", verbose); try { driver<SString<char> >(infile, infiles, snp_fname, ht_fname, ss_fname, exon_fname, sv_fname, outfile, false, REF_READ_FORWARD); } catch(bad_alloc& e) { if(autoMem) { cerr << "Switching to a packed string representation." << endl; packed = true; } else { throw e; } } } return 0; } catch(std::exception& e) { cerr << "Error: Encountered exception: '" << e.what() << "'" << endl; cerr << "Command: "; for(int i = 0; i < argc; i++) cerr << argv[i] << " "; cerr << endl; deleteIdxFiles(outfile, writeRef || justRef, justRef); return 1; } catch(int e) { if(e != 0) { cerr << "Error: Encountered internal HISAT2 exception (#" << e << ")" << endl; cerr << "Command: "; for(int i = 0; i < argc; i++) cerr << argv[i] << " "; cerr << endl; } deleteIdxFiles(outfile, writeRef || justRef, justRef); return e; }}
开发者ID:cooleel,项目名称:hisat2,代码行数:101,
示例22: timerStatusWith<DistLockManager::ScopedDistLock> ReplSetDistLockManager::lock( OperationContext* txn, StringData name, StringData whyMessage, milliseconds waitFor, milliseconds lockTryInterval) { Timer timer(_serviceContext->getTickSource()); Timer msgTimer(_serviceContext->getTickSource()); // Counts how many attempts have been made to grab the lock, which have failed with network // error. This value is reset for each lock acquisition attempt because these are // independent write operations. int networkErrorRetries = 0; // Distributed lock acquisition works by tring to update the state of the lock to 'taken'. If // the lock is currently taken, we will back off and try the acquisition again, repeating this // until the lockTryInterval has been reached. If a network error occurs at each lock // acquisition attempt, the lock acquisition will be retried immediately. while (waitFor <= milliseconds::zero() || milliseconds(timer.millis()) < waitFor) { const OID lockSessionID = OID::gen(); const string who = str::stream() << _processID << ":" << getThreadName(); auto lockExpiration = _lockExpiration; MONGO_FAIL_POINT_BLOCK(setDistLockTimeout, customTimeout) { const BSONObj& data = customTimeout.getData(); lockExpiration = stdx::chrono::milliseconds(data["timeoutMs"].numberInt()); } LOG(1) << "trying to acquire new distributed lock for " << name << " ( lock timeout : " << durationCount<Milliseconds>(lockExpiration) << " ms, ping interval : " << durationCount<Milliseconds>(_pingInterval) << " ms, process : " << _processID << " )" << " with lockSessionID: " << lockSessionID << ", why: " << whyMessage; auto lockResult = _catalog->grabLock( txn, name, lockSessionID, who, _processID, Date_t::now(), whyMessage); auto status = lockResult.getStatus(); if (status.isOK()) { // Lock is acquired since findAndModify was able to successfully modify // the lock document. log() << "distributed lock '" << name << "' acquired for '" << whyMessage << "', ts : " << lockSessionID; return ScopedDistLock(txn, lockSessionID, this); } // If a network error occurred, unlock the lock synchronously and try again if (ShardRegistry::kAllRetriableErrors.count(status.code()) && networkErrorRetries < kMaxNumLockAcquireRetries) { LOG(1) << "Failed to acquire distributed lock because of retriable error. Retrying " "acquisition by first unlocking the stale entry, which possibly exists now" << causedBy(status); networkErrorRetries++; status = _catalog->unlock(txn, lockSessionID); if (status.isOK()) { // We certainly do not own the lock, so we can retry continue; } // Fall-through to the error checking logic below invariant(status != ErrorCodes::LockStateChangeFailed); LOG(1) << "Failed to retry acqusition of distributed lock. No more attempts will be made" << causedBy(status); } if (status != ErrorCodes::LockStateChangeFailed) { // An error occurred but the write might have actually been applied on the // other side. Schedule an unlock to clean it up just in case. queueUnlock(lockSessionID); return status; } // Get info from current lock and check if we can overtake it. auto getLockStatusResult = _catalog->getLockByName(txn, name); const auto& getLockStatus = getLockStatusResult.getStatus(); if (!getLockStatusResult.isOK() && getLockStatus != ErrorCodes::LockNotFound) { return getLockStatus; } // Note: Only attempt to overtake locks that actually exists. If lock was not // found, use the normal grab lock path to acquire it. if (getLockStatusResult.isOK()) { auto currentLock = getLockStatusResult.getValue(); auto canOvertakeResult = canOvertakeLock(txn, currentLock, lockExpiration); if (!canOvertakeResult.isOK()) { return canOvertakeResult.getStatus(); } if (canOvertakeResult.getValue()) { auto overtakeResult = _catalog->overtakeLock(txn, name, lockSessionID, currentLock.getLockID(),//.........这里部分代码省略.........
开发者ID:dingzhengkai,项目名称:robomongo-shell,代码行数:101,
示例23: timervoid VoxelManipulator::addArea(const VoxelArea &area){ // Cancel if requested area has zero volume if (area.hasEmptyExtent()) return; // Cancel if m_area already contains the requested area if(m_area.contains(area)) return; TimeTaker timer("addArea", &addarea_time); // Calculate new area VoxelArea new_area; // New area is the requested area if m_area has zero volume if(m_area.hasEmptyExtent()) { new_area = area; } // Else add requested area to m_area else { new_area = m_area; new_area.addArea(area); } s32 new_size = new_area.getVolume(); /*dstream<<"adding area "; area.print(dstream); dstream<<", old area "; m_area.print(dstream); dstream<<", new area "; new_area.print(dstream); dstream<<", new_size="<<new_size; dstream<<std::endl;*/ // Allocate new data and clear flags MapNode *new_data = new MapNode[new_size]; assert(new_data); u8 *new_flags = new u8[new_size]; assert(new_flags); memset(new_flags, VOXELFLAG_NO_DATA, new_size); // Copy old data s32 old_x_width = m_area.MaxEdge.X - m_area.MinEdge.X + 1; for(s32 z=m_area.MinEdge.Z; z<=m_area.MaxEdge.Z; z++) for(s32 y=m_area.MinEdge.Y; y<=m_area.MaxEdge.Y; y++) { unsigned int old_index = m_area.index(m_area.MinEdge.X,y,z); unsigned int new_index = new_area.index(m_area.MinEdge.X,y,z); memcpy(&new_data[new_index], &m_data[old_index], old_x_width * sizeof(MapNode)); memcpy(&new_flags[new_index], &m_flags[old_index], old_x_width * sizeof(u8)); } // Replace area, data and flags m_area = new_area; MapNode *old_data = m_data; u8 *old_flags = m_flags; /*dstream<<"old_data="<<(int)old_data<<", new_data="<<(int)new_data <<", old_flags="<<(int)m_flags<<", new_flags="<<(int)new_flags<<std::endl;*/ m_data = new_data; m_flags = new_flags; delete[] old_data; delete[] old_flags; //dstream<<"addArea done"<<std::endl;}
开发者ID:DaErHuo,项目名称:minetest,代码行数:76,
示例24: timervoid StaticContentCache::load() { Timer timer(Timer::WallTime, "loading static content"); if (!RuntimeOption::FileCache.empty()) { TheFileCache = std::make_shared<FileCache>(); TheFileCache->loadMmap(RuntimeOption::FileCache.c_str()); Logger::Info("loaded file cache from %s", RuntimeOption::FileCache.c_str()); return; } int rootSize = RuntimeOption::SourceRoot.size(); if (rootSize == 0) return; // get a list of all files, one for each extension Logger::Info("searching all files under source root..."); int count = 0; std::map<std::string, std::vector<std::string> > ext2files; { const char *argv[] = {"", (char*)RuntimeOption::SourceRoot.c_str(), "-type", "f", nullptr}; std::string files; std::vector<std::string> out; Process::Exec("find", argv, nullptr, files); Util::split('/n', files.c_str(), out, true); for (unsigned int i = 0; i < out.size(); i++) { const std::string &name = out[i]; size_t pos = name.rfind('.'); if (pos != std::string::npos) { ext2files[name.substr(pos+1)].push_back(name); ++count; } } } Logger::Info("analyzing %d files under source root...", count); for (auto iter = RuntimeOption::StaticFileExtensions.begin(); iter != RuntimeOption::StaticFileExtensions.end(); ++iter) { if (ext2files.find(iter->first) == ext2files.end()) { continue; } const std::vector<std::string> &out = ext2files[iter->first]; int total = 0; for (unsigned int i = 0; i < out.size(); i++) { auto const f = std::make_shared<ResourceFile>(); auto const sb = std::make_shared<CstrBuffer>(out[i].c_str()); if (sb->valid() && sb->size() > 0) { std::string url = out[i].substr(rootSize + 1); f->file = sb; m_files[url] = f; // prepare gzipped content, skipping image and swf files if (iter->second.find("image/") != 0 && iter->first != "swf") { int len = sb->size(); char *data = gzencode(sb->data(), len, 9, CODING_GZIP); if (data) { if (unsigned(len) < sb->size()) { f->compressed = std::make_shared<CstrBuffer>(data, len); } else { free(data); } } } total += sb->size(); } } Logger::Info("..loaded %d bytes of %s files", total, iter->first.c_str()); m_totalSize += total; } Logger::Info("loaded %d bytes of static content in total", m_totalSize);}
开发者ID:Alienfeel,项目名称:hhvm,代码行数:75,
示例25: foutvoid Detection::TestBs(){ std::ofstream fout("text.txt", std::ofstream::ate|std::ofstream::app); fout << "/n**********************************************************************/n"; fout << "10. TestBS" << std::endl; std::string bss[3]; bss[0] = "ppvabs.pplive.com"; bss[1] = "ppvaindex.pplive.com"; bss[2] = "60.28.216.149"; for (int i = 0; i < 3; ++i) { boost::asio::io_service io_service; boost::asio::ip::udp::resolver resolver(io_service); boost::asio::ip::udp::resolver::query query(boost::asio::ip::udp::v4(), bss[i], ""); boost::asio::ip::udp::endpoint receiver_endpoint = *resolver.resolve(query); receiver_endpoint.port(6400); boost::asio::ip::udp::socket socket(io_service); socket.open(boost::asio::ip::udp::v4()); std::string send_buffer = ""; boost::uint32_t check_sum = 0x80301a7d; boost::uint8_t action = 0x14; boost::uint32_t transaction_id = 0x00000006; boost::uint8_t is_request = 1; boost::uint16_t peer_version = 0x0106; boost::uint16_t reserved = 0x0000; boost::uint32_t guid_1 = 0x36e985d8; boost::uint32_t guid_2 = 0x4e4e041d; boost::uint32_t guid_3 = 0x8a7db9b7; boost::uint32_t guid_4 = 0x911a6af6; send_buffer.append((const char *)&check_sum, 4); send_buffer.append((const char *)&action, 1); send_buffer.append((const char *)&transaction_id, 4); send_buffer.append((const char *)&is_request, 1); send_buffer.append((const char *)&peer_version, 2); send_buffer.append((const char *)&reserved, 2); send_buffer.append((const char *)&guid_1, 4); send_buffer.append((const char *)&guid_2, 4); send_buffer.append((const char *)&guid_3, 4); send_buffer.append((const char *)&guid_4, 4); socket.send_to(boost::asio::buffer(send_buffer), receiver_endpoint); boost::asio::ip::udp::endpoint sender_endpoint; boost::asio::deadline_timer timer(io_service); socket.async_receive_from( boost::asio::buffer(data_, 2000), sender_endpoint, boost::bind(&Detection::HandleReceiveFrom, this, 0, 0, boost::ref(timer), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); timer.expires_from_now(boost::posix_time::seconds(5)); timer.async_wait(boost::bind(&Detection::TimeOutHandler, this, 0, boost::asio::placeholders::error, boost::ref(socket), 0)); io_service.run(); if (has_tracker_list) { m_progress_pos_ = 135; break; } } fout.close();}
开发者ID:huangyt,项目名称:MyProjects,代码行数:68,
示例26: pvoid BDPTIntegrator::Render(const Scene &scene) { ProfilePhase p(Prof::IntegratorRender); // Compute _lightDistr_ for sampling lights proportional to power std::unique_ptr<Distribution1D> lightDistr = ComputeLightPowerDistribution(scene); // Partition the image into tiles Film *film = camera->film; const Bounds2i sampleBounds = film->GetSampleBounds(); const Vector2i sampleExtent = sampleBounds.Diagonal(); const int tileSize = 16; const int nXTiles = (sampleExtent.x + tileSize - 1) / tileSize; const int nYTiles = (sampleExtent.y + tileSize - 1) / tileSize; ProgressReporter reporter(nXTiles * nYTiles, "Rendering"); // Allocate buffers for debug visualization const int bufferCount = (1 + maxDepth) * (6 + maxDepth) / 2; std::vector<std::unique_ptr<Film>> weightFilms(bufferCount); if (visualizeStrategies || visualizeWeights) { for (int depth = 0; depth <= maxDepth; ++depth) { for (int s = 0; s <= depth + 2; ++s) { int t = depth + 2 - s; if (t == 0 || (s == 1 && t == 1)) continue; char filename[32]; snprintf(filename, sizeof(filename), "bdpt_d%02i_s%02i_t%02i.exr", depth, s, t); weightFilms[BufferIndex(s, t)] = std::unique_ptr<Film>(new Film( film->fullResolution, Bounds2f(Point2f(0, 0), Point2f(1, 1)), std::unique_ptr<Filter>(CreateBoxFilter(ParamSet())), film->diagonal * 1000, filename, 1.f)); } } } // Render and write the output image to disk if (scene.lights.size() > 0) { StatTimer timer(&renderingTime); ParallelFor([&](const Point2i tile) { // Render a single tile using BDPT MemoryArena arena; int seed = tile.y * nXTiles + tile.x; std::unique_ptr<Sampler> tileSampler = sampler->Clone(seed); int x0 = sampleBounds.pMin.x + tile.x * tileSize; int x1 = std::min(x0 + tileSize, sampleBounds.pMax.x); int y0 = sampleBounds.pMin.y + tile.y * tileSize; int y1 = std::min(y0 + tileSize, sampleBounds.pMax.y); Bounds2i tileBounds(Point2i(x0, y0), Point2i(x1, y1)); std::unique_ptr<FilmTile> filmTile = camera->film->GetFilmTile(tileBounds); for (Point2i pPixel : tileBounds) { tileSampler->StartPixel(pPixel); do { // Generate a single sample using BDPT Point2f pFilm = (Point2f)pPixel + tileSampler->Get2D(); // Trace the camera and light subpaths Vertex *cameraVertices = arena.Alloc<Vertex>(maxDepth + 2); Vertex *lightVertices = arena.Alloc<Vertex>(maxDepth + 1); int nCamera = GenerateCameraSubpath( scene, *tileSampler, arena, maxDepth + 2, *camera, pFilm, cameraVertices); int nLight = GenerateLightSubpath( scene, *tileSampler, arena, maxDepth + 1, cameraVertices[0].time(), *lightDistr, lightVertices); // Execute all BDPT connection strategies Spectrum L(0.f); for (int t = 1; t <= nCamera; ++t) { for (int s = 0; s <= nLight; ++s) { int depth = t + s - 2; if ((s == 1 && t == 1) || depth < 0 || depth > maxDepth) continue; // Execute the $(s, t)$ connection strategy and // update _L_ Point2f pFilmNew = pFilm; Float misWeight = 0.f; Spectrum Lpath = ConnectBDPT( scene, lightVertices, cameraVertices, s, t, *lightDistr, *camera, *tileSampler, &pFilmNew, &misWeight); if (visualizeStrategies || visualizeWeights) { Spectrum value; if (visualizeStrategies) value = misWeight == 0 ? 0 : Lpath / misWeight; if (visualizeWeights) value = Lpath; weightFilms[BufferIndex(s, t)]->AddSplat( pFilmNew, value); } if (t != 1) L += Lpath; else film->AddSplat(pFilmNew, Lpath); } } filmTile->AddSample(pFilm, L);//.........这里部分代码省略.........
开发者ID:richardjpurcell,项目名称:pbrt-v3,代码行数:101,
示例27: resolvervoid Detection::TestTracker(){// std::ofstream fout("text.txt", std::ofstream::ate|std::ofstream::app);// fout << "/n**********************************************************************/n";// fout << "11. TestTracker" << std::endl;// fout.close(); std::string send_buffer = ""; boost::uint32_t check_sum = 0x66e3d105; boost::uint8_t action = 0x31; boost::uint32_t transaction_id = 0x00054afb; boost::uint8_t is_request = 1; boost::uint16_t peer_version = 0x0106; boost::uint16_t reserved = 0x0000; boost::uint32_t rid_1 = 0x4c58186d; boost::uint32_t rid_2 = 0x45cab895; boost::uint32_t rid_3 = 0x47d10c08; boost::uint32_t rid_4 = 0xf4354547; boost::uint32_t guid_1 = 0xa111fe6e; boost::uint32_t guid_2 = 0x4e1472c3; boost::uint32_t guid_3 = 0x9298e98b; boost::uint32_t guid_4 = 0x825f3f99; boost::uint16_t peer_count = 0x0032; send_buffer.append((const char *)&check_sum, 4); send_buffer.append((const char *)&action, 1); send_buffer.append((const char *)&transaction_id, 4); send_buffer.append((const char *)&is_request, 1); send_buffer.append((const char *)&peer_version, 2); send_buffer.append((const char *)&reserved, 2); send_buffer.append((const char *)&rid_1, 4); send_buffer.append((const char *)&rid_2, 4); send_buffer.append((const char *)&rid_3, 4); send_buffer.append((const char *)&rid_4, 4); send_buffer.append((const char *)&guid_1, 4); send_buffer.append((const char *)&guid_2, 4); send_buffer.append((const char *)&guid_3, 4); send_buffer.append((const char *)&guid_4, 4); send_buffer.append((const char *)&peer_count, 2); for (int i = 0; i < m_tracker_infos.size(); ++i) { boost::asio::io_service io_service; boost::asio::ip::udp::resolver resolver(io_service); boost::asio::ip::udp::resolver::query query(boost::asio::ip::udp::v4(), m_tracker_infos[i].ip, ""); boost::asio::ip::udp::endpoint receiver_endpoint = *resolver.resolve(query); receiver_endpoint.port(m_tracker_infos[i].port); boost::asio::ip::udp::socket socket(io_service); socket.open(boost::asio::ip::udp::v4()); socket.send_to(boost::asio::buffer(send_buffer), receiver_endpoint); boost::asio::ip::udp::endpoint sender_endpoint; boost::asio::deadline_timer timer(io_service); socket.async_receive_from( boost::asio::buffer(data_, 2000), sender_endpoint, boost::bind(&Detection::HandleReceiveFrom, this, 1, i, boost::ref(timer), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); timer.expires_from_now(boost::posix_time::seconds(5)); timer.async_wait(boost::bind(&Detection::TimeOutHandler, this, 1, boost::asio::placeholders::error, boost::ref(socket), i)); io_service.run(); }}
开发者ID:huangyt,项目名称:MyProjects,代码行数:69,
示例28: Aobject//.........这里部分代码省略......... char st2[256]; sprintf(str, "%d", i+1); sprintf(st2, "midi channel #%d", i+1); new Aitem(str, st2, psetItems, i, this); } } new Aitem("[all]", "all channels", psetItems, 16, this); midiIn=new Amlist("midi in devices", this, 100, 160, pos.w-120, 50, midiInItems); midiIn->setTooltips("midi in devices"); midiIn->show(TRUE); midiOut=new Alist("midi out devices", this, 100, 220, pos.w-120, 20, midiOutItems); midiOut->setCurrentByData(((MYwindow *)father)->table->midiOutDevice); midiOut->setTooltips("midi out devices"); midiOut->show(TRUE); pset=new Alist("pset", this, 100, 250, pos.w-120, 20, psetItems); pset->setCurrentByData(((MYwindow *)father)->table->midiProgChangeChannel); pset->setTooltips("presets - program change event midi channel"); pset->show(TRUE); sndsize=new Aselsize("sndsize", this, 100, 280, pos.w-120, 20); sndsize->set(((MYwindow *)father)->table->dsoundsize); { char str[256]; float v=(sndsize->get()*(float)(DSOUNDSIZE-DSOUNDSIZEMIN)+(float)DSOUNDSIZEMIN)/(44100.f*2.f); // 2x >> double event buffer sprintf(str, "%5.2f ms", v*1000.f); sndsize->set(str); } sndsize->setTooltips("direct sound buffer latency"); sndsize->show(true); timer(500);}/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////Aconfig::~Aconfig(){ ((MYwindow *)father)->config=NULL; delete(close); //delete(regist); delete(resList); delete(resItems); delete(rateList); delete(rateItems); delete(timeList); delete(timeItems); delete(cmpList); delete(cmpItems); //delete(render); //delete(priority); delete(midiIn); delete(midiInItems); delete(midiOut); delete(midiOutItems); delete(pset); delete(psetItems); //delete(splash); delete(tips); ((MYwindow *)father)->settings();}//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
开发者ID:RaymondLiao,项目名称:elektronika,代码行数:67,
示例29: AccessSenderlword NetworkSink::DoFlush(unsigned long maxTime, size_t targetSize){ NetworkSender &sender = AccessSender(); bool forever = maxTime == INFINITE_TIME; Timer timer(Timer::MILLISECONDS, forever); unsigned int totalFlushSize = 0; while (true) { if (m_buffer.CurrentSize() <= targetSize) break; if (m_needSendResult) { if (sender.MustWaitForResult() && !sender.Wait(SaturatingSubtract(maxTime, timer.ElapsedTime()), CallStack("NetworkSink::DoFlush() - wait send result", 0))) break; unsigned int sendResult = sender.GetSendResult();#if CRYPTOPP_TRACE_NETWORK OutputDebugString((IntToString((unsigned int)this) + ": Sent " + IntToString(sendResult) + " bytes/n").c_str());#endif m_buffer.Skip(sendResult); totalFlushSize += sendResult; m_needSendResult = false; if (!m_buffer.AnyRetrievable()) break; } unsigned long timeOut = maxTime ? SaturatingSubtract(maxTime, timer.ElapsedTime()) : 0; if (sender.MustWaitToSend() && !sender.Wait(timeOut, CallStack("NetworkSink::DoFlush() - wait send", 0))) break; size_t contiguousSize = 0; const byte *block = m_buffer.Spy(contiguousSize);#if CRYPTOPP_TRACE_NETWORK OutputDebugString((IntToString((unsigned int)this) + ": Sending " + IntToString(contiguousSize) + " bytes/n").c_str());#endif sender.Send(block, contiguousSize); m_needSendResult = true; if (maxTime > 0 && timeOut == 0) break; // once time limit is reached, return even if there is more data waiting } m_byteCountSinceLastTimerReset += totalFlushSize; ComputeCurrentSpeed(); if (m_buffer.IsEmpty() && !m_needSendResult) { if (m_eofState == EOF_PENDING_SEND) { sender.SendEof(); m_eofState = sender.MustWaitForEof() ? EOF_PENDING_DELIVERY : EOF_DONE; } while (m_eofState == EOF_PENDING_DELIVERY) { unsigned long timeOut = maxTime ? SaturatingSubtract(maxTime, timer.ElapsedTime()) : 0; if (!sender.Wait(timeOut, CallStack("NetworkSink::DoFlush() - wait EOF", 0))) break; if (sender.EofSent()) m_eofState = EOF_DONE; } } return totalFlushSize;}
开发者ID:Andy-Amoy,项目名称:cryptopp,代码行数:73,
注:本文中的timer函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 C++ timerEvent函数代码示例 C++ timeout_set函数代码示例 |