void annotation(Float_t a=10, Float_t d=5, Float_t x=0, Float_t y=0, Float_t z=0) { TEveManager::Create(); // add a box in scene TEveBox* b = new TEveBox("Box", "Test Title"); b->SetMainColor(kCyan); b->SetMainTransparency(0); b->SetVertex(0, x - a, y - a, z - a); b->SetVertex(1, x - a, y + a, z - a); b->SetVertex(2, x + a, y + a, z - a); b->SetVertex(3, x + a, y - a, z - a); b->SetVertex(4, x - a, y - a, z + a); b->SetVertex(5, x - a, y + a, z + a); b->SetVertex(6, x + a, y + a, z + a); b->SetVertex(7, x + a, y - a, z + a); gEve->AddElement(b); gEve->Redraw3D(kTRUE); // add overlay text TGLViewer* v = gEve->GetDefaultGLViewer(); TDatime time; TGLAnnotation* ann = new TGLAnnotation(v, time.AsString(), 0.1, 0.9); ann->SetTextSize(0.1);// % of window diagonal // set timer to update text every second MyTimer* timer = new MyTimer(ann); timer->SetTime(1000); timer->Reset(); timer->TurnOn(); }
int main(int argc, char** argv) { int n = argc > 1 ? atoi(argv[1]) : 0; typedef Board T; //typedef BoardPlus T; MyTimer timer; switch (n) { case 1: timer.start("construct part"); ContainerBenchmark<ContainerWrapper<ptr_vector<T>>>()(timer); timer.stop(); break; case 2: timer.start("construct part"); ContainerBenchmark<ContainerWrapper<boost::ptr_vector<T>>>()(timer); timer.stop(); break; case 3: timer.start("construct part"); ContainerBenchmark<ContainerWrapper<std::vector<std::shared_ptr<T>>>>()(timer); timer.stop(); break; case 4: timer.start("construct part"); ContainerBenchmark<ContainerWrapper<std::vector<T>>>()(timer); timer.stop(); break; } timer.showResults(); }
int main(int argc, char** argv) { //const int loop_size = 1000000; const int loop_size = 100000; //const int thread_size = std::thread::hardware_concurrency(); const int thread_size = 2; std::cout << "thread_size = " << thread_size << std::endl; MyTimer timer; benchmark<lock_based_queue>("lock_based_queue", timer, thread_size, loop_size); benchmark<lock_based_stack>("lock_based_stack", timer, thread_size, loop_size); benchmark<boost_lock_free_queue>("boost_lock_free_queue", timer, thread_size, loop_size); benchmark<boost_lock_free_stack>("boost_lock_free_stack", timer, thread_size, loop_size); /* WorkerThreadGroup<lock_based_queue<std::shared_ptr<BenchMarkTask> > > bm_worker_lbspg(thread_size); timer.start("lock_based_queue<std::shared_ptr<BenchMarkTask> > group"); for(int i=0; i<loop_size; ++i) { bm_worker_lbspg.submit(std::make_shared<BenchMarkTask>()); } bm_worker_lbspg.join(); timer.stop(); */ /* WorkerThread<lock_free_queue, BenchMarkJobPolicy> bm_worker_lf; timer.start("lock_free_queue<BenchMarkTask>"); for(int i=0; i<loop_size; ++i) { bm_worker_lf.post(BenchMarkJob()); } bm_worker_lf.join(); timer.stop(); std::cout << "total_counter: " << BenchMarkResource::total_counter << std::endl; */ /* WorkerThreadGroup<lock_free_queue, BenchMarkJobPolicy> bm_worker_lfg(thread_size); timer.start("lock_free_queue<BenchMarkTask>"); for(int i=0; i<loop_size; ++i) { bm_worker_lfg.post(BenchMarkJob()); } bm_worker_lfg.join(); timer.stop(); std::cout << "total_counter: " << BenchMarkResource::total_counter << std::endl; */ AsioThreadPool<BenchmarkInitPolicy, BenchmarkEndPolicy> thread_pool(thread_size); timer.start("AsioThreadPool"); for(int i=0; i<loop_size; ++i) { thread_pool.post(BenchmarkTask()); } thread_pool.join(); timer.stop(); std::cout << "total_counter: " << total_counter << std::endl; //std::cout << "result.value(): " << result.value() << std::endl; timer.showResults(); }
int main(int argc, char **argv) { MyTimer<microsec_clock> t; for(int i = 0; i < 100; ++i) { cout << "hello" << endl; } t.Elapsed(); return 0; }
void GamePlay::Loop(sf::RenderWindow* target,TextureManager* textureManager) { sf::Event MyEvent; MyTimer fps = MyTimer(1000/resource::consts::FPS); int frame = 0; fps.StartTimer(); int key_down = 0; while(_running) { if(frame % resource::consts::FPS == 0) { while(target->GetEvent(MyEvent)) { _player->UpdateKey(MyEvent,_offSet,_map); switch(MyEvent.Type) { case sf::Event::KeyPressed: key_down = 1; switch(MyEvent.Key.Code) { case sf::Key::Escape: _running = false; break; } break; case sf::Event::KeyReleased: key_down = false; break; } } if(!key_down) { _player->UpdateVelocity(_map); } target->Clear(); _player->UpdatePosition(); _player->CollosionLogic(_map); Render(target,textureManager); } target->Display(); frame++; if( fps.GetTicks() < 1000 / resource::consts::FPS ) { //Sleep the remaining frame time // SDL_Delay( ( 1000 / resource::consts::FPS ) - fps.GetTicks() ); } } }
// Accessing cell; will do dense voting if cell not there yet TensorCell& TensorMap::operator[](const CellKey& key) { cell_access_timer.start(); try { dense_map.at(key); cell_access_timer.stop(); //cout << "Hit: "<<key.i<<", "<<key.j<<", "<<key.k<<endl; return dense_map.at(key); } catch (out_of_range& oor) { //cout << "Miss: "<<key.i<<", "<<key.j<<", "<<key.k<<endl; computeDenseVoting(key); cell_access_timer.stop(); return dense_map.at(key); } }
void MyControlBarWindow::draw() { // the draw method must be private _controlbar_viewer.set(CONTROLBAR_WIDTH,CONTROLBAR_HEIGHT,0); _controlbar_viewer.setup2D(); _controlbar_viewer.clearWindow(true); glDisable(GL_LIGHTING); int x = 10; int y = CONTROLBAR_HEIGHT-20; _controlbar_viewer.drawBox(0,0,CONTROLBAR_WIDTH,CONTROLBAR_HEIGHT,2,RED); _controlbar_viewer.displayMsg(x,y,"Control Bar",RED,0); y -= 20; // print the time MyTimer timer; _controlbar_viewer.displayMsg(x,y,(char*)timer.timestring().c_str(),RED,0); y -= 20; // print info // print performance time _controlbar_viewer.displayMsg(x,y,RED,0,"Frame ID: %d",_main_w_ptr->frameId); y -= 20; // print synthetic mode _controlbar_viewer.displayMsg(x,y,RED,0,"# correspondences: %d",_main_w_ptr->_n_correspondences); y -= 20; /*if ( !_main_w_ptr->correspondence_distribution.empty() ) { // print the distribution _controlbar_viewer.displayMsg(x, y, BLUE, 0, "CONNECTED: %d", _main_w_ptr->correspondence_distribution[0] ); y -= 20; _controlbar_viewer.displayMsg(x, y, BLUE, 0, "EXPECTED: %d", _main_w_ptr->correspondence_distribution[1] ); y -= 20; _controlbar_viewer.displayMsg(x, y, BLUE, 0, "BLACKLISTED: %d", _main_w_ptr->correspondence_distribution[2] ); y -= 20; } */ // print VP scores _controlbar_viewer.displayMsg(x,y,RED,0,"VP Score: %.4f", scoreSetsOfVanishingPoints(_main_w_ptr->_LUT._vps, _main_w_ptr->_vpc, toRadians(10.0))); };
void benchmark(std::string benchmark_name, MyTimer& timer, const int thread_size, const int loop_size) { WorkerThread<Container, BenchmarkJobPolicy> worker_solo; timer.start(benchmark_name); for(int i=0; i<loop_size; ++i) { worker_solo.post(typename BenchmarkJobPolicy::job_type()); } worker_solo.join(); timer.stop(); std::cout << "total_counter: " << BenchmarkResource::total_counter << std::endl; WorkerThreadGroup<Container, BenchmarkJobPolicy> worker(thread_size); timer.start(benchmark_name + " group"); for(int i=0; i<loop_size; ++i) { //if (i < 100) usleep(10000); worker.post(typename BenchmarkJobPolicy::job_type()); } worker.join(); timer.stop(); std::cout << "total_counter: " << BenchmarkResource::total_counter << std::endl; WorkerThreadGroup<lock_based_queue, BenchmarkJobPointerPolicy> worker_p(thread_size); timer.start(benchmark_name + " pointer"); for(int i=0; i<loop_size; ++i) { worker_p.post(new BenchmarkJob); } worker_p.join(); timer.stop(); std::cout << "total_counter: " << BenchmarkResource::total_counter << std::endl; }
// 模拟交互过程的函数 unsigned _int64 TestHL::ProtocolFun(const int& tag){ // 获取被选标签的信息 string sql; sql = "select [Id], [Key] from Tags_HL where Num="; sql.append(itostr(tag)); adoConn.GetRecordSet(sql.c_str()); if (adoConn.m_pRecordset->GetState() == adStateClosed || adoConn.m_pRecordset->GetRecordCount() == 0) { cout << endl << "Tag[" << tag << "] isn't in DataBase." << endl; return 0; } // 生成查询信息 Request_Info req; req.id= adoConn.m_pRecordset->GetCollect("Id").uintVal; req.key = adoConn.m_pRecordset->GetCollect("Key").uintVal; adoConn.CloseRecordset(); // 计时器 MyTimer timer; // 初始化随机数生成器 minstd_rand0 minrand(timer.GetBegin()); timer.Start(); // 调用模拟标签的函数 Response_Info res = TagFun(req); // 调用阅读器的函数 Result_Info result = ReaderFun(res); // 计时器终止 timer.Stop(); return timer.GetTime(); }
void testare_convolutie(const char *fisier_semnal, const char *fisier_filtru) { MyTimer timer; int w_baza = (int)pow(2, 17); baza = new ZZ(w_baza); int lambda = 112; cout << "Securitate = " << lambda << " biti" << endl; cout << "Baza = " << w_baza << endl; vector<int> semnal; vector<int> filtru; vector<int> convolutie; citeste_semnal(fisier_semnal, semnal); citeste_semnal(fisier_filtru, filtru); /*srand(time(NULL)); for (int i = 0; i < 10; i++) { semnal[i] = rand() % 256 - 128; filtru[i] = rand() % 256 - 128; } cout << "Semnal = [ "; for (int i = 0; i < semnal.size(); i++) { cout << semnal[i] << " "; } cout << " ]" << endl << "Filtru = [ "; for (int i = 0; i < filtru.size(); i++) { cout << filtru[i] << " "; } cout << " ] " << endl;*/ vector<Mat_ZZ> semnal_criptat; vector<Mat_ZZ> filtru_criptat; vector<Mat_ZZ> conv_criptata; HE_Signal he_signal(lambda, w_baza); cout << "creare he_signal - terminata.\n"; cout << "criptare semnale ...\n"; timer.start_timer(); he_signal.cripteaza_semnal(semnal, semnal_criptat); cout << "Timp criptare semnal : " << timer.stop_timer << endl; timer.start_timer(); he_signal.cripteaza_semnal(filtru, filtru_criptat); cout << "Timp criptare filtru : " << timer.stop_timer() << endl; cout << "criptare semnale - terminat.\n"; /*vector<int> dec_s1; vector<int> dec_s2; he_signal.decripteaza_semnal(dec_s1, semnal_criptat); he_signal.decripteaza_semnal(dec_s2, filtru_criptat); scrie_semnal("dec1.dat", dec_s1); scrie_semnal("dec2.dat", dec_s2); cout << "scriere semnale decriptate -terminat .\n";*/ timer.start_timer(); cout << "incepe convolutia semnalelor criptate\n"; he_signal.convolutie_semnale(semnal_criptat, filtru_criptat, conv_criptata); cout << "timp convolutie criptata = " << timer.stop_timer() << endl; timer.start_timer(); convolutie_semnale(semnal, filtru, convolutie); cout << "timp convolutie in clar = " << timer.stop_timer() << endl; vector<int> conv_dec; he_signal.decripteaza_semnal(conv_dec, conv_criptata); assert(convolutie.size() == conv_dec.size()); for (int i = 0; i < convolutie.size(); i++) { if (convolutie[i] != conv_dec[i]) { cout << "Semnale diferite\n"; break; } } }
// Get map from point cloud void TensorMap::import(const PointCloud& point_cloud) { // filtering distance_filter_timer.start(); sparse_map = distance_filter(point_cloud); distance_filter_timer.stop(); // clearing dense map dense_map.clear(); /* sparse voting */ sparse_voting_timer.start(); // nearest neighbor search const SparseVotingParams& params = tensor_map_params->sparse_voting; const int maxNbPts = params.max_knn; // max number of neighbors const float sigma = params.sigma; // sigma parameter for tensor voting const float max_dist = params.max_dist; // maximum distance for knn const float sigma2 = pow(sigma, 2); kdTree.reset(NNSearchF::create(sparse_map.features, sparse_map.features.rows()-1, NNSearchF::KDTREE_TREE_HEAP)); // matches and search NNSearchF::IndexMatrix indices(maxNbPts, sparse_map.features.cols()); NNSearchF::Matrix dists2(maxNbPts, sparse_map.features.cols()); kdTree->knn(sparse_map.features, indices, dists2, maxNbPts, 0, NNSearchF::SORT_RESULTS, max_dist); // new rows for tensors PointCloud::Labels labels; labels.push_back({"eigen_values", 3}); labels.push_back({"eigen_vectors", 9}); sparse_map.allocateDescriptors(labels); auto eigen_values = sparse_map.getDescriptorViewByName("eigen_values"); auto eigen_vectors = sparse_map.getDescriptorViewByName("eigen_vectors"); const auto eye3 = Matrix3f::Identity(); // actual voting for (int i=0; i<sparse_map.features.cols(); ++i) { //cout << "\rSparse voting from neighbors: " << i << "/" << // sparse_map.features.cols()<<":"; cout.flush(); const Vector3f voter = sparse_map.features.col(i).head(3); // compute tensor for voter Matrix3f tensor = Matrix3f::Zero(); for (int j=0; j<maxNbPts; ++j) { if (dists2(j, i) == numeric_limits<float>::infinity()) { break; } const Vector3f votee = sparse_map.features.col(indices(j, i)).head(3); const Matrix3f vv = (votee-voter)*((votee-voter).transpose()); const float n_vv = fabs(((votee-voter).transpose())*(votee-voter)); tensor += exp(-dists2(j, i)/sigma2)*(eye3 - vv/n_vv); } // decompose tensor const EigenSolver<Matrix3f> solver(tensor); Vector3f eigenVals = solver.eigenvalues().real(); Matrix3f eigenVectors = solver.eigenvectors().real(); sortTensor(eigenVals, eigenVectors); MatrixXf e_v(eigenVectors); e_v.resize(9, 1); // store into point cloud eigen_values.col(i) = eigenVals; eigen_vectors.col(i) = e_v; } //cout << endl; sparse_voting_timer.stop(); }
int main(int argc, char *argv[]) { if (argc != 4) { printf("Insertion Sort C++\n\n"\ "uso : %s metodo insertion_sort input_file output_file\n"\ "ejm. : %s is input/n1m.txt output/o-n1m.txt\n", argv[0], argv[0]); exit(-1); } //Número de palabras int num_palabras; // Object containing information to control a stream FILE *infile_ptr = NULL; FILE *outfile_ptr = NULL; //Open file for input operations. The file must exist. infile_ptr = fopen(argv[2], "r+"); outfile_ptr = fopen(argv[3], "w+"); // Timer MyTimer mt; int tiempo_total = 0; printf("Leer archivo... "); mt.Start(); // read count char count[MAX_ANCHO_LINEA]; // Get - Leer numero de lineas ubicadas en la cabecera del archivo // esto es para determinar cuanto de memoria debemos separar // el valor es solo aproximado, para una mejor gestion if (fgets(count, MAX_ANCHO_LINEA, infile_ptr) != NULL) { num_palabras = atoi(count); } // Array de lineas LINE *w_arr; w_arr = (LINE *)calloc(num_palabras, sizeof(LINE)); NODE *n_arr, *n_head, *n_cur; n_arr = (NODE *)calloc(num_palabras, sizeof(NODE)); n_head = n_arr; // read words int linea; int num_lineas = 0; for (linea = 0; !feof(infile_ptr); linea++) { // using fgets() is faster, but there is '\n' at the end of the string. fgets(w_arr[linea].data, MAX_ANCHO_LINEA, infile_ptr); n_arr[linea].vp = w_arr[linea].data; //printf("n_arr[%i]=%s\n", linea, n_arr[linea].vp); n_arr[linea].next = &n_arr[linea + 1]; ++num_lineas; } n_arr[linea - 1].next = NULL; fclose(infile_ptr); mt.Stop(); printf("%d ms\n", (int)mt.d_costTime); tiempo_total += (int)mt.d_costTime; // sorting printf("Ordenando... "); mt.Start(); // obtener Método de Ordenamiento de los parámetros if ( strcmp(argv[1], "insertion_sort") == 0) { insertion_sort(n_arr, num_lineas - 1 ); } else { printf("Metodo no Implementado... "); return 0;//exit } mt.Stop(); printf("%d ms\n", (int)mt.d_costTime); tiempo_total += (int)mt.d_costTime; // write to file printf("Escribir archivo... "); mt.Start(); fputs(count, outfile_ptr); n_cur = n_head; while (1) { fputs(n_cur->vp, outfile_ptr); if (n_cur->next == NULL) break; n_cur = n_cur->next; } fclose(outfile_ptr); mt.Stop(); printf("%d ms\n", (int)mt.d_costTime); tiempo_total += (int)mt.d_costTime; printf("Tiempo total en: %d ms\n", tiempo_total); free(w_arr); free(n_arr); return 0; }
TagAlignments* readData(const ArgumentParser &args) {//{{{ long i,j,num,tid; double prb; long Ntotal=0,Nmap=0,probM=0; string readId,strand,blank; ifstream inFile; MyTimer timer; TagAlignments *alignments = new TagAlignments(false); // Read alignment probabilities {{{ inFile.open(args.args()[0].c_str()); FileHeader fh(&inFile); ns_fileHeader::AlignmentFileType format; if((!fh.probHeader(&Nmap,&Ntotal,&probM,&format)) || (Nmap ==0)){//{{{ error("Prob file header read failed.\n"); return NULL; }//}}} // Use number of transcripts from prob file if it is higher. if(probM>M)M = probM; message("N mapped: %ld\n",Nmap); messageF("N total: %ld\n",Ntotal); if(args.verb())message("Reading alignments.\n"); if(Ntotal>Nmap)Nunmap=Ntotal-Nmap; else Nunmap=1; //no valid count file assume only one not aligned properly alignments->init(Nmap,0,M); long mod=10000; long bad = 0; timer.start(); for(i = 0; i < Nmap; i++) { inFile>>readId>>num; if(format==ns_fileHeader::OLD_FORMAT)inFile>>blank; if(!inFile.good())break; // message("%s %ld\n",(readId).c_str(),num); for(j = 0; j < num; j++) { if(format == ns_fileHeader::OLD_FORMAT)inFile>>tid>>strand>>prb; else inFile>>tid>>prb; if(inFile.fail()){ inFile.clear(); // ignore other read's alignments j=num; // this read goes to noise assigning tid=0; // 10 means either 10 or exp(10), but should be still be large enough prb=10; bad++; } switch(format){ case ns_fileHeader::OLD_FORMAT: if(tid!=0) prb /= trInfo.L(tid-1); case ns_fileHeader::NEW_FORMAT: alignments->pushAlignment(tid, prb); break; case ns_fileHeader::LOG_FORMAT: alignments->pushAlignmentL(tid, prb); } } // ignore rest of line inFile.ignore(10000000,'\n'); alignments->pushRead(); R_INTERUPT; if(args.verb() && (i % mod == 0) && (i>0)){ message(" %ld ",i); timer.split(); mod*=10; } }
// the main entry point for the application is this function void DarkGDK ( void ){ // Seed the random number generator srand(time(NULL)); // Configure the engine to run as fast as possible (no frame rate cap) dbSyncOn(); dbSyncRate(0); // If fullscreen, configure to a, currently, hard coded setting if (FULLSCREEN) { dbSetWindowOff(); dbMaximizeWindow(); dbSetDisplayModeAntialias(1680, 1050, 32, 1, 0, 0); dbSetCameraAspect(0, 1680.0 / 1050.0); } // Otherwise, configure a windowed display else { dbSetDisplayModeAntialias(1280, 800, 32, 1, 0, 0); dbSetCameraAspect(0, 1280.0 / 800.0); int winPosX = (dbDesktopWidth() - dbScreenWidth()) / 2; int winPosY = (dbDesktopHeight() - dbScreenHeight()) / 2; dbSetWindowPosition(winPosX, winPosY); } // Hide the mouse pointer; CEGUI handles this dbHideMouse(); // This forces the timer to initialise MyTimer *timer = &MyTimer::get(); float t; // Create a new Game State - this is a general game controlling class BiPlaneGameState *gsGame = new BiPlaneGameState(); // We'll need a start-up menu StartMenuGameState *gsMenu = new StartMenuGameState(); // a Loop State holder bool loopState = TRUE; // This is for the Start Menu loop //while (LoopGDK()) { do { // Tick the timer & frame rate for this loop timer->tick(); t = timer->getT(); dbText(0, 0, dbStr((float)(1.0 / t))); loopState &= gsGame->update(t); loopState &= gsMenu->update(t); dbSync(); } while (loopState && LoopGDK()); switch (gsMenu->getState()) { // Start Server case 1 : break; // Start Client case 2 : break; // SOMETHING WENT WRONG!! default : exit(-5); } loopState = TRUE; // our main loop //while (LoopGDK()) { do { // Tick the timer & frame rate for this loop timer->tick(); t = timer->getT(); dbText(0, 0, dbStr((float)(1.0 / t))); // Issue an Update to the GameState system, passing the frameTime into it loopState &= gsGame->update(t); // Update the display dbSync(); } while (loopState && LoopGDK()); // Do a little house keeping delete gsGame; delete gsMenu; return; }
void VariationalBayes::optimize(bool verbose,OPT_TYPE method,long maxIter,double ftol, double gtol){//{{{ bool usedSteepest; long iteration=0,i,r; double boundOld,bound,squareNorm,squareNormOld=1,valBeta=0,valBetaDiv,natGrad_i,gradGamma_i,phiGradPhiSum_r; double *gradPhi,*natGrad,*gradGamma,*searchDir,*tmpD,*phiOld; gradPhi=natGrad=gradGamma=searchDir=tmpD=phiOld=NULL; MyTimer timer; // allocate stuff {{{ //SimpleSparse *phiGradPhi=new SimpleSparse(beta); gradPhi = new double[T]; // phiOld = new double[T]; will use gradPhi memory for this phiOld = NULL; natGrad = new double[T]; if(method == OPTT_HS) gradGamma = new double[T]; searchDir = new double[T]; //searchDirOld = new double[T]; //phiGradPhi_sum = new double[N]; // }}} #ifdef LOG_CONV ofstream logF(logFileName.c_str()); logF.precision(15); logF<<"# iter bound squareNorm time(m) [M*means M*vars]"<<endl; if(logTimer)logTimer->setQuiet(); #ifdef LONG_LOG vector<double> dirAlpha(M); #endif #endif boundOld=getBound(); timer.start(); while(true){ negGradient(gradPhi); // "yuck" //setVal(phiGradPhi,i,phi->val[i]*gradPhi[i]); //phiGradPhi->sumRows(phiGradPhi_sum); // removed need for phiGradPhi matrix: // removed need for phiGradPhi_sum /*for(r=0;r<N;r++){ phiGradPhi_sum[r] = 0; for(i=phi->rowStart[r];i<phi->rowStart[r+1];i++) phiGradPhi_sum[r] += phi->val[i] * gradPhi[i]; }*/ // set natGrad & gradGamma squareNorm=0; valBeta = 0; valBetaDiv = 0; #pragma omp parallel for private(i,phiGradPhiSum_r,natGrad_i,gradGamma_i) reduction(+:squareNorm,valBeta,valBetaDiv) for(r=0;r<N;r++){ phiGradPhiSum_r = 0; for(i = phi->rowStart[r]; i < phi->rowStart[r+1]; i++) phiGradPhiSum_r += phi->val[i] * gradPhi[i]; for(i = phi->rowStart[r]; i < phi->rowStart[r+1]; i++){ natGrad_i = gradPhi[i] - phiGradPhiSum_r; gradGamma_i = natGrad_i * phi->val[i]; squareNorm += natGrad_i * gradGamma_i; if(method==OPTT_PR){ valBeta += (natGrad_i - natGrad[i])*gradGamma_i; } if(method==OPTT_HS){ valBeta += (natGrad_i-natGrad[i])*gradGamma_i; valBetaDiv += (natGrad_i-natGrad[i])*gradGamma[i]; gradGamma[i] = gradGamma_i; } natGrad[i] = natGrad_i; } } if((method==OPTT_STEEPEST) || (iteration % (N*M)==0)){ valBeta=0; }else if(method==OPTT_PR ){ // already computed: // valBeta=0; // for(i=0;i<T;i++)valBeta+= (natGrad[i]-natGradOld[i])*gradGamma[i]; valBeta /= squareNormOld; }else if(method==OPTT_FR ){ valBeta = squareNorm / squareNormOld; }else if(method==OPTT_HS ){ // already computed: //valBeta=div=0; //for(i=0;i<T;i++){ // valBeta += (natGrad[i]-natGradOld[i])*gradGamma[i]; // div += (natGrad[i]-natGradOld[i])*gradGammaOld[i]; //} if(valBetaDiv!=0)valBeta /= valBetaDiv; else valBeta = 0; } if(valBeta>0){ usedSteepest = false; //for(i=0;i<T;i++)searchDir[i]= -natGrad[i] + valBeta*searchDirOld[i]; // removed need for searchDirOld: #pragma omp parallel for for(i=0;i<T;i++) searchDir[i]= -natGrad[i] + valBeta*searchDir[i]; }else{ usedSteepest = true; #pragma omp parallel for for(i=0;i<T;i++) searchDir[i]= -natGrad[i]; } //try conjugate step SWAPD(gradPhi,phiOld); memcpy(phiOld,phi_sm->val,T*sizeof(double)); // memcpy(phiOld,pack(),T*sizeof(double)); unpack(phiOld,searchDir); bound = getBound(); iteration++; // make sure there is an increase in L, else revert to steepest if((bound<boundOld) && (valBeta>0)){ usedSteepest = true; #pragma omp parallel for for(i=0;i<T;i++) searchDir[i]= -natGrad[i]; unpack(phiOld,searchDir); bound = getBound(); // this should not be increased: iteration++; } if(bound<boundOld) { // If bound decreased even after using steepest, step back and quit. unpack(phiOld); } SWAPD(gradPhi,phiOld); if(verbose){ #ifdef SHOW_FIXED messageF("iter(%c): %5.ld bound: %.3lf grad: %.7lf beta: %.7lf fixed: %ld\n",(usedSteepest?'s':'o'),iteration,bound,squareNorm,valBeta,phi->countAboveDelta(0.999)); #else messageF("iter(%c)[%5.lds]: %5.ld bound: %.3lf grad: %.7lf beta: %.7lf\n",(usedSteepest?'s':'o'),(long)timer.getTime(),iteration,bound,squareNorm,valBeta); #endif }else if(!quiet){ messageF("\riter(%c): %5.ld bound: %.3lf grad: %.7lf beta: %.7lf ",(usedSteepest?'s':'o'),iteration,bound,squareNorm,valBeta); } #ifdef LOG_CONV if((iteration%100==0) || ((iteration<500) && (iteration%50==0)) || ((iteration<150) && (iteration%10==0)) || ((iteration<50) && (iteration%5==0))){ logF<<iteration<<" "<<bound<<" "<<squareNorm; if(logTimer)logF<<" "<<logTimer->current(0,'m'); #ifdef LONG_LOG double alphaSum = 0, alphaVarNorm; // True 'alpha' - Dirichlet parameter is alpha+phiHat. for(i=1;i<M;i++){ dirAlpha[i] = alpha[i] + phiHat[i]; alphaSum += dirAlpha[i]; } for(i=1;i<M;i++)logF<< " " << dirAlpha[i] / alphaSum; alphaVarNorm = alphaSum*alphaSum*(alphaSum+1); for(i=1;i<M;i++)logF<<" "<<dirAlpha[i]*(alphaSum-dirAlpha[i])/alphaVarNorm; #endif logF<<endl; } #endif // convergence check {{{ if(bound<boundOld){ message("\nEnd: bound decrease\n"); break; } if(abs(bound-boundOld)<=ftol){ message("\nEnd: converged (ftol)\n"); break; } if(squareNorm<=gtol){ message("\nEnd: converged (gtol)\n"); break; } if(iteration>=maxIter){ message("\nEnd: maxIter exceeded\n"); break; } // }}} // store essentials {{{ squareNormOld=squareNorm; boundOld=bound; // }}} R_INTERUPT; } if(quiet){ messageF("iter(%c): %5.ld bound: %.3lf grad: %.7lf beta: %.7lf\n",(usedSteepest?'s':'o'),iteration,bound,squareNorm,valBeta); } #ifdef LOG_CONV logF<<iteration<<" "<<bound<<" "<<squareNorm; if(logTimer)logF<<" "<<logTimer->current(0,'m'); #ifdef LONG_LOG double alphaSum = 0, alphaVarNorm; // True 'alpha' - Dirichlet parameter is alpha+phiHat. for(i=1;i<M;i++){ dirAlpha[i] = alpha[i] + phiHat[i]; alphaSum += dirAlpha[i]; } for(i=1;i<M;i++)logF<< " " << dirAlpha[i] / alphaSum; alphaVarNorm = alphaSum*alphaSum*(alphaSum+1); for(i=1;i<M;i++)logF<<" "<<dirAlpha[i]*(alphaSum-dirAlpha[i])/alphaVarNorm; #endif logF<<endl; if(logTimer)logTimer->setVerbose(); logF.close(); #endif // free memory {{{ //delete phiGradPhi; delete[] gradPhi; delete[] natGrad; if(method == OPTT_HS) delete[] gradGamma; delete[] searchDir; //delete[] searchDirOld; //delete[] phiGradPhi_sum; // }}} }//}}}
//------------------------------------------------------------------------------ int main(int argc, char *argv[]) { if (argc == 3) { TestReader::Tests tests; if ( TestReader::read(argv[1], tests) ) { std::ofstream ofl(argv[2], std::ios_base::out | std::ios_base::trunc); if (ofl) { RankerCfg rankerCfg; rankerCfg.setBegin(0); rankerCfg.setEnd(1000); rankerCfg.setCount(THREADS_NUM); auto const ranks = Ranker::doRank(rankerCfg); std::cout << "Threads count = " << THREADS_NUM << std::endl; MyTimer allTestsTimer; for (size_t i = 0, n = tests.size(); i < n; ++i) { MyTimer testTimer; auto const test = tests[i]; std::cout << "Test#" << i << " bombs : [ "; for (auto const &bomb : test) { std::cout << "(x : " << bomb.x() << ", y : " << bomb.y() << ", z : " << bomb.z() << ") "; } std::cout << "]" << std::endl; std::vector< WorkerPtr > workers; for (auto const rank : ranks) { WorkerCfg workerCfg; workerCfg.setSideSize(1000); workerCfg.setXBegin(rank.first); workerCfg.setXEnd(rank.second); workerCfg.setTest(test); auto worker = std::make_shared< Worker >(workerCfg); workers.push_back(worker); auto thread = std::thread( &Worker::execute, worker.get() ); thread.detach(); } Maxer< int > maxDistanceSquared(-1); for (auto const &worker : workers) { auto const safeDistanceSquared = worker->safeDistanceSquared(); maxDistanceSquared.setValue(safeDistanceSquared); } // write to file ofl << maxDistanceSquared.value() << std::endl; std::cout << "Safe distance squared = " << maxDistanceSquared.value() << std::endl; std::cout << "Test#" << i << " duration " << testTimer.elapsedMs() << " ms" << std::endl; std::cout << "--------" << std::endl; } std::cout << "All tests duration " << allTestsTimer.elapsedMs() << " ms" << std::endl; } } else { std::cerr << "Fail open output file " << argv[2] << std::endl; } } else { std::cout << "Use " << argv[0] << " <input-file> <output-file>" << std::endl; } }
// Compute dense voting TensorCell& TensorMap::computeDenseVoting(const CellKey& key) { // timing dense_voting_timer.start(); // getting parameters const DenseVotingParams& params = tensor_map_params->dense_voting; const int maxNbPts = params.max_knn; // max number of neighbors const float sigma = params.sigma; // tensor voting parameter const float max_dist = params.max_dist; // maximum radius const Vector3f& cell_dims = tensor_map_params->cell_dimensions; //const float cell2 = cell_dims.squaredNorm()/4; const float obs_dir_offset = params.obs_dir_offset; const float absolute_saliency_threshold = params.absolute_saliency_threshold; // position of the point in space const Vector3f position(indexToPosition(key)); // data in the point cloud auto eigen_vectors = sparse_map.getDescriptorViewByName("eigen_vectors"); auto eigen_values = sparse_map.getDescriptorViewByName("eigen_values"); auto obsDirection = sparse_map.getDescriptorViewByName\ ("observationDirections"); // tensor to vote into Matrix3f tensor = Matrix3f::Identity(); // getting observation direction from closest point to realign normal float min_dist2 = numeric_limits<float>::infinity(); int closest_index = -1; // nearest neighbor search of points for voters VectorXi indices(maxNbPts); VectorXf dists2(maxNbPts); kdTree->knn(position, indices, dists2, maxNbPts, 0, NNSearchF::SORT_RESULTS, max_dist); // going through all neighboring points of the center of the cell int nb_points = 0; int i; for (i = 0; i<maxNbPts; ++i) { if (dists2(i) == numeric_limits<float>::infinity()) { // no match anymore break; } if (dists2(i) == 0.) { // null vote ++nb_points; continue; } int index = indices(i); // closest point for the point of view if (dists2(i)<min_dist2) { min_dist2 = dists2(i); closest_index = index; } // counting the number of points in the cell const Vector3f voter = sparse_map.features.col(index).head(3); if (((voter-position).array().abs() <= (cell_dims/2).array()).all()) { ++nb_points; } /* * Full tensor voting */ const Vector3f v = position - voter; Vector3f v_hat; if (v.isZero()) { v_hat = v; } else { v_hat = v.normalized(); } // saliencies float saliencies[3]; saliencies[0] = eigen_values(0, index) - eigen_values(1, index); saliencies[1] = eigen_values(1, index) - eigen_values(2, index); saliencies[2] = eigen_values(2, index); MatrixXf e_vectors(eigen_vectors.col(index)); e_vectors.resize(3, 3); // normal spaces Matrix3f normal_spaces[3]; normal_spaces[0] = e_vectors.col(0) * (e_vectors.col(0).transpose()); normal_spaces[1] = normal_spaces[0] + e_vectors.col(1) * (e_vectors.col(1).transpose()); normal_spaces[2] = normal_spaces[1] + e_vectors.col(2) * (e_vectors.col(2).transpose()); // accumulator for all votes of this voter Matrix3f A = Matrix3f::Zero(); // loop for all 3 votes for (int d=0; d<3; ++d) { // normal vector const Vector3f v_n = normal_spaces[d] * v; Vector3f v_n_hat; if (v_n.isZero()) { v_n_hat = v_n; } else { v_n_hat = v_n.normalized(); } // tangent vector const Vector3f v_t = v - v_n; Vector3f v_t_hat; if (v_t.isZero()) { v_t_hat = v_t; } else { v_t_hat = v_t.normalized(); } // normal for votee const float cos_theta = v_hat.dot(v_t_hat); const float sin_theta = v_hat.dot(v_n_hat); const float cos_2theta = 2*pow(cos_theta, 2) - 1; const float sin_2theta = 2*cos_theta*sin_theta; const Vector3f v_c_hat = cos_2theta * v_n_hat - sin_2theta * v_t_hat; // weight functions // using n=4 as in King FIXME const float w_angle = pow(cos_theta, 2*4); const float z = v.norm()/sigma; const float w_dist = pow(z,2)*(pow((z-3),4))/16; // vote for this dimension const Matrix3f A_d = w_dist*w_angle*v_c_hat*v_c_hat.transpose() + w_dist*(normal_spaces[d] - v_n_hat*v_n_hat.transpose()); A += saliencies[d] * A_d; } // standard voting FIXME //tensor += A; // normalized voting FIXME tensor += A / (eigen_values(0, index) + absolute_saliency_threshold); // /* // old vote // actual vote Vector3f e_v = position - voter; const float r = sqrt(dists2(i)); e_v /= r; const float stick_sal = eigen_values(0, index) - eigen_values(1, index); MatrixXf e_vectors(eigen_vectors.col(index)); e_vectors.resize(3, 3); const Vector3f v_n = e_vectors.col(0); const Vector3f v_t = v_n.cross(e_v.cross(v_n)); const float cos_theta = e_v.dot(v_t); const float theta = atan2(e_v.dot(v_n), cos_theta); // Decoupled weighting profile for angle and distance // Angle based weighting const float w_angle = pow(cos_theta,4); // Distance based weighting const float z = r/sigma; const float w_dist = pow(z,2)*(pow((z-3),2))/16; // stick vote // could compute sin and cos based on cos_theta and sin_theta FIXME const Vector3f v_c = v_n*cos(2*theta) - v_t*sin(2*theta); const float w = w_angle*w_dist; tensor += stick_sal*w*v_c*v_c.transpose(); //tensor += stick_sal*w*v_c*v_c.transpose()/(eigen_values(0, index) + absolute_saliency_threshold); */ } // analyse resulting tensor const EigenSolver<Matrix3f> solver(tensor); Vector3f eigenVals = solver.eigenvalues().real(); Matrix3f eigenVectors = solver.eigenvectors().real(); sortTensor(eigenVals, eigenVectors); float stick_sal = eigenVals(0)-eigenVals(1); float s = eigenVals(0)-eigenVals(1); //float p = eigenVals(1)-eigenVals(2); //float b = eigenVals(2); float Z = eigenVals(0); //cout << "Saliency distribution: (" << s/Z << ", " << p/Z << ", " << b/Z << "); abs_sal=" << Z << "; p_plane=" << s/(Z+absolute_saliency_threshold) << " (" << absolute_saliency_threshold << ")" << endl; Vector3f normal; if (closest_index == -1) { // no point at all normal = {0., 0., 0.}; stick_sal = 0.; } else { // flip normal according to closest point const Vector3f obsDir = obsDirection.col(closest_index)+ Vector3f(0, 0, obs_dir_offset); const Vector3f v_n = eigenVectors.col(0); if (obsDir.dot(v_n)<0.) { normal = -v_n; } else { normal = v_n; } } dense_map.insert({key, TensorCell(position, stick_sal, normal, nb_points, UNKNOWN, s/(Z+absolute_saliency_threshold)) }); // stopping timer dense_voting_timer.stop(); return dense_map.at(key); }
void operator()(MyTimer& timer) { typename Container::Element elem; container_.reserve(LOOPSIZE); timer.stop(); // end of construct part timer.start("push_back part"); timer.pause(); for (int i=0; i<LOOPSIZE; ++i) { elem.fill_rand(); // timer ignores the time consumption of this function call timer.resume(); container_.push_back(elem); timer.pause(); } timer.stop(); // end of push_back part timer.start("sort part"); container_.sort(); timer.stop(); // end od sort part std::cout << "container size before unique: " << container_.size() << std::endl; timer.start("unique part"); container_.unique(); timer.stop(); // end of uniue part std::cout << "container size after unique: " << container_.size() << std::endl; timer.start("destruct part"); }
int main(){ srand((unsigned int)time(NULL)); gettimeofday(&globalStartTime,NULL); MyServer *server; // MyClientManage *clientManage; std::map<std::string,std::string> keyMap; char *configFileName = "./config/simulator.cfg"; ParseConfigFile(configFileName,keyMap); double serverBand,clientBand; int blockSize,perSendSize; bool isP2POpen; int fileNum; int maxLength,minLength; double minBitRate,maxBitRate; int serverFd; int blockNums,serverBlockNums; //add by sunpy string bufferStrategy; int period; double lrfuLambda; //add end int thelta,lambda,zeta,sigma; int playToPlay,playToPause,playToForward,playToBackward,playToStop; int clientNums; int devNums; char *clusterAddress[MAX_DEV_NUM]; int serverPort; int clientPort; int sampleFre; bool isUseRealDevice; serverBand = atof(keyMap["ServerBand"].c_str()); clientBand = atof(keyMap["ClientBand"].c_str()); blockSize = atoi(keyMap["BlockSize"].c_str()); perSendSize = atoi(keyMap["PerSendSize"].c_str()); isP2POpen = !strcmp(keyMap["isP2POpen"].c_str(),"true") ? true : false; fileNum = atoi(keyMap["SourceNums"].c_str()); maxLength = atoi(keyMap["MaxLength"].c_str()); minLength = atoi(keyMap["MinLength"].c_str()); minBitRate = atof(keyMap["MinBitRate"].c_str()); maxBitRate = atof(keyMap["MaxBitRate"].c_str()); blockNums = atoi(keyMap["BlockNums"].c_str()); //add by sunpy serverBlockNums = atoi(keyMap["ServerBlockNums"].c_str()); bufferStrategy = keyMap["BufferStrategy"]; period = atoi(keyMap["Period"].c_str()); lrfuLambda = atoi(keyMap["LrfuLambda"].c_str()); //add end thelta = atoi(keyMap["Thelta"].c_str()); lambda = atoi(keyMap["Lambda"].c_str()); zeta = atoi(keyMap["Zeta"].c_str()); sigma = atoi(keyMap["Sigma"].c_str()); playToPlay = atoi(keyMap["PlayToPlay"].c_str()); playToPause = atoi(keyMap["PlayToPause"].c_str()); playToForward = atoi(keyMap["PlayToForward"].c_str()); playToBackward = atoi(keyMap["PlayToBackward"].c_str()); playToStop = atoi(keyMap["PlayToStop"].c_str()); clientNums = atoi(keyMap["ClientNums"].c_str()); devNums = atoi(keyMap["DevNums"].c_str()); serverPort = atoi(keyMap["ServerPort"].c_str()); clientPort = atoi(keyMap["ClientPort"].c_str()); sampleFre = atoi(keyMap["SampleFrequency"].c_str()); globalModify = atof(keyMap["Modify"].c_str()); isUseRealDevice = !strcmp(keyMap["IsUseRealDevice"].c_str(),"true") ? true : false; int multiple = atoi(keyMap["Multiple"].c_str()); globalTimer.setMultiple(multiple); stringstream sstring; for(int i = 0;i < devNums;i++){ sstring.str(""); sstring << "ClusterAddress" << (i + 1); string keyName = sstring.str(); clusterAddress[i] = const_cast<char *>(keyMap[keyName.c_str()].c_str()); } server = new MyServer(serverBand,blockSize,serverBlockNums,bufferStrategy,period,lrfuLambda,perSendSize,isP2POpen,fileNum,maxLength,minLength, minBitRate,maxBitRate,serverPort,clientPort,devNums,clientNums,clusterAddress,sampleFre,isUseRealDevice); // clientManage = new MyClientManage(serverFd,perSendSize,blockSize,blockNums,clientBand,fileNum,thelta,lambda, // zeta,sigma,playToPlay,playToPause,playToForward,playToBackward,playToStop,clientNums); // // cout << "create clients" << endl; // clientManage->CreateClient(); // sleep(10); pthread_join(server->GetTid(),NULL); keyMap.clear(); delete server; // delete clientManage; // exit(0); return 0; }
void SuiteTimerBasic::Test() { MyTimer a(iEnv); TUint i=0; for( ; i < 100; i++ ) { a.FireIn(300); Thread::Sleep(iEnv.Random(30, 10)); Print("."); } #if 0 a.Wait(); TUint count0 = a.Count(); Thread::Sleep(3000); TUint count1 = a.Count(); TEST(count0 == count1); for( i=0; i < 100; i++ ) { a.FireIn(300); TUint j = iEnv.Random(3500, 2500); TUint k=0; for( ; k < j; k++) { Print("."); } } a.Wait(); Thread::Sleep(3000); MyTimer b(iEnv); Print("\nWait for 5 seconds\n"); a.FireIn(5000); a.Wait(); Print("Wait finished\n"); Print("Wait for 3 seconds then a further 2 seconds\n"); a.FireIn(5000); b.FireIn(3000); b.Wait(); Print("Wait finished 1\n"); a.Wait(); Print("Wait finished 2\n"); for (TUint j = 1; j < 21; j++) { Print("Wait for 1 second then a further %d millisecond\n", j); a.FireIn(1000); b.FireIn(1000 + j); a.Wait(); Print("Wait finished 1\n"); b.Wait(); Print("Wait finished 2\n"); } Print("Wait for 0 seconds\n"); a.FireIn(0); a.Wait(); Print("Wait finished\n"); Print("Cancel a timer\n"); MyTimer c(iEnv); a.FireIn(1000); c.FireIn(2000); b.FireIn(3000); a.Wait(); Print("Wait finished 1\n"); TEST(c.Count() == 0); c.Cancel(); b.Wait(); Print("Wait finished 2\n"); TEST(c.Count() == 0); Print("Delete a timer\n"); MyTimer* d = new MyTimer(iEnv); a.FireIn(1000); d->FireIn(2000); b.FireIn(3000); a.Wait(); Print("Wait finished 1\n"); TEST(d->Count() == 0); delete d; b.Wait(); Print("Wait finished 2\n"); Print("Change a timer\n"); // Replaced 'a' with a new timer 'a2', as this code // assumes the MyTimer sema count is 0. Not guaranteed though :( MyTimer a2(iEnv); MyTimer e(iEnv); a2.FireIn(1000); e.FireIn(2000); b.FireIn(3000); a2.Wait(); Print("Wait finished 1\n"); TEST(e.Count() == 0); e.FireIn(3000); b.Wait(); Print("Wait finished 2\n"); TEST(e.Count() == 0); e.Wait(); Print("Wait finished 3\n"); TEST(e.Count() == 1); #endif }
int main(int argc, char **argv) { if (!init()) { return 1; } if (!loadMedia()) { return 2; } SDL_Event e; bool running = true; MyTimer timer; std::stringstream ss; while (running) { while (SDL_PollEvent(&e)) { if (e.type == SDL_KEYDOWN) { switch (e.key.keysym.sym) { case SDLK_RETURN: if (timer.isStarted()) timer.stop(); else timer.start(); break; case SDLK_p: if (timer.isPaused()) timer.unpause(); else timer.pause(); break; default: break; } } if (e.type == SDL_QUIT) { running = false; } } ss.str(""); ss << "Milliseconds from start time: " << timer.getTicks(); //draw something SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0xff); SDL_RenderClear(renderer); promptText->rendering((800 - promptText->getWidth()) / 2, 0); promptText2->rendering((800 - promptText2->getWidth()) / 2, promptText->getHeight()); timerText->loadText(TTF_OpenFont("font/Amble-Bold.ttf", 30), ss.str().c_str(), { 0, 0xff, 0}, { 0, 0, 0 }); timerText->rendering((800 - timerText->getWidth()) / 2, (600 - timerText->getHeight()) / 2); SDL_RenderPresent(renderer); } close(); return 0; }
int main( int argc, const char ** argv ) { // Get params // pm-simple.exe polyADegree polyBDegree if (argc != 3) { std::cout << "Simple Random Poly Multiply C++" << std::endl; std::cout << "Uso: pm-simple.exe polyADegree polyBDegree" << std::endl; std::cout << "Ejm: pm-simple.exe 5 6" << std::endl; return 0; } // Set vars int rdADegree = std::atoi( argv[1] ); int rdBDegree = std::atoi( argv[2] ); // Conditions: // Array coefficients corresponding to degrees // in ascending order (i.e. {5, 0, 10, 6} = 5 + 10x^2 + 6x^3 // Generate two polys, on random sizes // Bug en Windows si le das mas de 7 // [1-2] Range // unsigned int rdADegree = (unsigned int)rand() % 2 + 1 ; // unsigned int rdBDegree = (unsigned int)rand() % 2 + 1; #ifdef TRACE std::cout << "rdADegree: " << rdADegree << std::endl; std::cout << "rdBDegree: " << rdBDegree << std::endl; #endif // Coef rdADegree + 1 std::vector<int> coefA( rdADegree + 1 ); std::vector<int> coefB( rdBDegree + 1); // Setting random values // Populate random srand(time(NULL)); for (unsigned int i = 0; i < coefA.size(); i++) { // [-10,10] Range // totalOfIntegers = limitSuperior - limitInferior + 1 coefA[i] = rand() % 21 + (-10); } for (unsigned int j = 0; j < coefB.size(); j++) { // [-10,10] Range coefB[j] = rand() % 21 + (-10); } #ifdef TRACE // Print Random Polys std::cout << "Random Poly A " << std::endl; print_poly( coefA ); std::cout << "Random Poly B " << std::endl; print_poly( coefB ); #endif MyTimer mt; unsigned int tiempoTotal = 0; mt.Start(); std::vector<int> producto = multiply(coefA,coefB); #ifdef TRACE std::cout << std::endl << "AxB: " << std::endl; print_poly(producto); #endif // stop timer mt.Stop(); tiempoTotal += (int) mt.d_costTime; std::cout << "Tiempo total multiplicacion (milisegundos): " << tiempoTotal << " ms" << std::endl; return 0; }
// Get traversability of a pose bool TensorMap::isTraversable(const geometry_msgs::Pose& pose, bool v) { traversability_timer.start(); const Vector3f position(poseToVector(pose)); const CellKey& key(positionToIndex(position)); const TensorCell& cell((*this)[key]); // check it is easily traversable if (isEasilyTraversable(key)) { traversability_timer.stop(); return true; } // if not, check in details // getting parameters const TraversabilityParams& params = tensor_map_params->traversability; const float min_stick_sal = params.min_saliency; const float max_orientation_angle = params.max_slope; const int stick_sal_threshold = params.max_points_in_free_cell; const float min_free_cell_ratio = params.min_free_cell_ratio; const int nb_max_points = params.max_points_in_bounding_box; const int nb_min_support = params.min_support_points; const float length = params.length; const float width = params.width; const float height = params.height; const float l_2 = length/2. + params.inflation; const float w_2 = width/2. + params.inflation; const float ground_buffer = params.ground_buffer; const float buf2 = ground_buffer/2; const float h_2 = height/2; const float h0_2 = (height + buf2)/2; const float h1_2 = (height - buf2)/2; // check for enough saliency if (cell.stick_sal<min_stick_sal) { if (v) { cout << "Saliency too low: "<<cell.stick_sal<<"/"<< min_stick_sal<<endl; } traversability_timer.stop(); return false; } // check orientation is correct if (cell.angle_to_vertical>max_orientation_angle) { if (v) { cout << "Angle too steep: "<<cell.angle_to_vertical<<"/"<< max_orientation_angle<<endl; } traversability_timer.stop(); return false; } /* * check absence of obstacle */ // align orientation to surface Matrix3f alignedAxes; alignQuaternion(pose.orientation, cell.normal, alignedAxes); Vector3f x = alignedAxes.col(0); Vector3f y = alignedAxes.col(1); Vector3f z = alignedAxes.col(2); // generate bounding box Vector3f max_corner = l_2*x.array().abs()+\ w_2*y.array().abs()+\ h0_2*z.array().abs(); Vector3f center = position + h_2*z; CellKey min_key = positionToIndex(center - max_corner); CellKey max_key = positionToIndex(center + max_corner); // shifted up to separate support layer FIXME center += (buf2/2)*z; // look through bounding box for possible obstacles float nb_robot_cells = 0.; float nb_ok_robot_cells = 0.; int nb_points_in_cells = 0; int nb_support_points = 0; for (int i=min_key.i; i<max_key.i+1; ++i) for (int j=min_key.j; j<max_key.j+1; ++j) for (int k=min_key.k; k<max_key.k+1; ++k) { // check cell is in the robot TensorCell c = (*this)[CellKey(i, j, k)]; Vector3f rel_pos = c.position - center; Vector3f rel_pos_aligned = alignedAxes.transpose()*rel_pos; float rel_x, rel_y, rel_z; rel_x = rel_pos_aligned(0); rel_y = rel_pos_aligned(1); rel_z = rel_pos_aligned(2); if ((fabs(rel_x)>l_2)||(fabs(rel_y)>w_2)) { continue; } if (fabs(rel_z)>h1_2) { if (fabs(rel_z+h_2)<buf2) { nb_support_points += c.nb_points; } } else { // check no obstacle nb_robot_cells += 1; if (c.nb_points<=stick_sal_threshold) { nb_ok_robot_cells += 1; } else if (c.angle_to_vertical <= max_orientation_angle) { nb_ok_robot_cells += 1; nb_points_in_cells += c.nb_points; } } } // exit if not enough free cells if ((nb_ok_robot_cells/nb_robot_cells)<min_free_cell_ratio) { if (v) { cout << "not enough free cells: "<< nb_ok_robot_cells<<"/"<< min_free_cell_ratio*nb_robot_cells<<" ("<< nb_robot_cells<<")"<<endl; } traversability_timer.stop(); return false; } if (nb_points_in_cells>nb_max_points) { if (v) { cout << "too many (ground) points in cells: "<< nb_points_in_cells<<"/"<<nb_max_points<<endl; } traversability_timer.stop(); return false; } if (nb_support_points<nb_min_support) { if (v) { cout << "too few support points in cells: "<< nb_support_points<<"/"<<nb_min_support<<endl; } traversability_timer.stop(); return false; } // cell seems valid if (v) { cout << "valid" << endl; } traversability_timer.stop(); return true; }
static void Timer_CB(void *userdata) { MyTimer *o = (MyTimer*)userdata; o->redraw(); Fl::repeat_timeout(0.25, Timer_CB, userdata); }
int main() { #if (OS_MAINSTKSIZE<(800/4)) #error "Requires RTX Main Thread stack size to be increased to about 800 bytes for printf()" #endif printf("Starting\n"); uint8_t id = accelerometer.readID(); printf("Device ID = 0x%02X (should be 0x1A)\n", id); printf("Doing simple calibration\n" "Make sure the device is level!\n"); report("Startup", accelerometer); waitMS(400); report("Startup", accelerometer); waitMS(400); report("Startup", accelerometer); waitMS(400); accelerometer.calibrateAccelerometer(); // Make sure we have new values waitMS(100); printf("After calibration\n"); #if 1 /** * Method 1 * * Create timers using static functions controlled by CMSIS::Timer class */ // Convenient to declare timer function as lambda function wrapping report() static auto timerFn = [](const void *arg) { const char *name = (const char *)arg; report(name, accelerometer); }; // Create timer instances CMSIS::Timer timer1(timerFn, (void*)("Th 1"), osTimerPeriodic); CMSIS::Timer timer2(timerFn, (void*)("Th 2"), osTimerPeriodic); // Start timers timer1.start(300); timer2.start(100); #else /** * Method 2 * * Use classes derived from CMSIS::TimerClass */ // Create timer instances static MyTimer timer1("Th 1"); static MyTimer timer2("Th 2"); // Start timers timer1.start(300); timer2.start(100); #endif for(;;) { report("main", accelerometer); CMSIS::Thread::delay(400); } }
int main(){ srand((unsigned int)time(NULL)); gettimeofday(&globalStartTime,NULL); // MyServer *server; MyClientManage *clientManage; std::map<std::string,std::string> keyMap; char *configFileName = "./config/simulator.cfg"; ParseConfigFile(configFileName,keyMap); double serverBand,clientBand; int blockSize,perSendSize; bool isP2POpen; int fileNum; int maxLength,minLength; double bitRate; int serverFd; int blockNums; int thelta,lambda,zeta,sigma; int playToPlay,playToPause,playToForward,playToBackward,playToStop; int clientNums; int devNums; char *clusterAddress[MAX_DEV_NUM]; int serverPort; int clientPort; int clusterNum; char *serverAddress; bool isStartTogether; char *bufferStrategy; int period; int lrfuLambda; bool isRepeat; bool special; serverBand = atof(keyMap["ServerBand"].c_str()); clientBand = atof(keyMap["ClientBand"].c_str()); blockSize = atoi(keyMap["BlockSize"].c_str()); perSendSize = atoi(keyMap["PerSendSize"].c_str()); isP2POpen = !strcmp(keyMap["isP2POpen"].c_str(),"true") ? true : false; isRepeat = !strcmp(keyMap["isRepeat"].c_str(),"true") ? true : false; special = !strcmp(keyMap["Special"].c_str(),"true") ? true : false; // globalReadList = !strcmp(keyMap["ReadList"].c_str(),"true") ? true : false; fileNum = atoi(keyMap["SourceNums"].c_str()); maxLength = atoi(keyMap["MaxLength"].c_str()); minLength = atoi(keyMap["MinLength"].c_str()); bitRate = atof(keyMap["BitRate"].c_str()); blockNums = atoi(keyMap["BlockNums"].c_str()); thelta = atoi(keyMap["Thelta"].c_str()); lambda = atoi(keyMap["Lambda"].c_str()); zeta = atoi(keyMap["Zeta"].c_str()); sigma = atoi(keyMap["Sigma"].c_str()); playToPlay = atoi(keyMap["PlayToPlay"].c_str()); playToPause = atoi(keyMap["PlayToPause"].c_str()); playToForward = atoi(keyMap["PlayToForward"].c_str()); playToBackward = atoi(keyMap["PlayToBackward"].c_str()); playToStop = atoi(keyMap["PlayToStop"].c_str()); clientNums = atoi(keyMap["ClientNums"].c_str()); devNums = atoi(keyMap["DevNums"].c_str()); serverPort = atoi(keyMap["ServerPort"].c_str()); clientPort = atoi(keyMap["ClientPort"].c_str()); clusterNum = atoi(keyMap["ClusterNum"].c_str()); isStartTogether = !strcmp(keyMap["IsStartTogether"].c_str(),"true") ? true : false; globalModify = atof(keyMap["Modify"].c_str()); serverAddress = const_cast<char *>(keyMap["ServerAddress"].c_str()); bufferStrategy = const_cast<char *>(keyMap["ClientBufStrategy"].c_str()); period = atoi(keyMap["Period"].c_str()); lrfuLambda = atoi(keyMap["LrfuLambda"].c_str()); int multiple = atoi(keyMap["Multiple"].c_str()); globalTimer.setMultiple(multiple); int preFetch = atoi(keyMap["PreFetch"].c_str()); stringstream sstring; for(int i = 0;i < devNums;i++){ sstring.str(""); sstring << "ClusterAddress" << (i + 1); string keyName = sstring.str(); clusterAddress[i] = const_cast<char *>(keyMap[keyName.c_str()].c_str()); } // server = new MyServer(serverBand,blockSize,perSendSize,isP2POpen,fileNum,maxLength,minLength, // bitRate,serverPort,clientPort,devNums,clientNums,clusterAddress); clientManage = new MyClientManage(serverAddress,perSendSize,blockSize,blockNums,clientBand,fileNum,thelta,lambda, zeta,sigma,playToPlay,playToPause,playToForward,playToBackward,playToStop,clientNums,clusterAddress, serverPort,clientPort,devNums,clusterNum,isStartTogether,bufferStrategy, period,lrfuLambda,isRepeat,preFetch,special); // cout << "create clients" << endl; clientManage->CreateClient(); sleep(1); pthread_join(clientManage->GetTid(),NULL); keyMap.clear(); // delete server; delete clientManage; // exit(0); return 0; }
void SuiteTimerBasic::Test() { MyTimer a; TUint i=0; for( ; i < 1000; i++ ) { a.FireIn(300); Thread::Current()->Sleep(Random(30, 10)); Print("."); } a.Wait(); TUint count0 = a.Count(); Thread::Current()->Sleep(3000); TUint count1 = a.Count(); TEST(count0 == count1); for( i=0; i < 100; i++ ) { a.FireIn(300); TUint j = Random(3500, 2500); TUint k=0; for( ; k < j; k++) { Print("."); } } a.Wait(); Thread::Current()->Sleep(3000); MyTimer b; Print("\nWait for 5 seconds\n"); a.FireIn(5000); a.Wait(); Print("Wait finished\n"); Print("Wait for 3 seconds then a further 2 seconds\n"); a.FireIn(5000); b.FireIn(3000); b.Wait(); Print("Wait finished 1\n"); a.Wait(); Print("Wait finished 2\n"); for (TUint i = 1; i < 21; i++) { Print("Wait for 1 second then a further %d millisecond\n", i); a.FireIn(1000); b.FireIn(1000 + i); a.Wait(); Print("Wait finished 1\n"); b.Wait(); Print("Wait finished 2\n"); } Print("Wait for 0 seconds\n"); a.FireIn(0); a.Wait(); Print("Wait finished\n"); Print("Cancel a timer\n"); MyTimer c; a.FireIn(1000); c.FireIn(2000); b.FireIn(3000); a.Wait(); Print("Wait finished 1\n"); TEST(c.Count() == 0); c.Cancel(); b.Wait(); Print("Wait finished 2\n"); TEST(c.Count() == 0); Print("Delete a timer\n"); MyTimer* d = new MyTimer(); a.FireIn(1000); d->FireIn(2000); b.FireIn(3000); a.Wait(); Print("Wait finished 1\n"); TEST(d->Count() == 0); delete d; b.Wait(); Print("Wait finished 2\n"); Print("Change a timer\n"); MyTimer e; a.FireIn(1000); e.FireIn(2000); b.FireIn(3000); a.Wait(); Print("Wait finished 1\n"); TEST(e.Count() == 0); e.FireIn(3000); b.Wait(); Print("Wait finished 2\n"); TEST(e.Count() == 0); e.Wait(); Print("Wait finished 3\n"); TEST(e.Count() == 1); }