int main(int argc, char** argv) { Chrono ch; Timer tm; ch.startChrono(); fstream logfile; logfile.open("results_knapsack.txt", ios::out); //remember the limit of the 4gb allocated space int dim[] = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000}; int local_threads[] = {0, 64, 128, 256, 512, 1024}; for (int k = 5; k < sizeof (local_threads) / sizeof (int); k++) {//local_threads for (int j = 9; j < sizeof (dim) / sizeof (int); j++) { TestData* test = new TestData(dim[j]); Knapsack *ksack = new Knapsack(*test); //1.Query the host system for OpenCL platform info ksack->queryOclPlatformInfo(&logfile); //2. Query the host for OpenCL devices ksack->queryOclDevice(&logfile); for (int i = 0; i < ksack->getNumDevices(); i++) { ksack->queryOclDeviceInfo(i, &logfile); //3. Create a context and a queue to associate the OpenCL devices. ksack->createContextQueue(i, &logfile); //4. Create programs that will run on one or more associated devices. ksack->createProgramBuild(i, &logfile); //5. Create memory objects on the host or on the device. //6. Copy memory data to the device as needed. Create memory objects on the host or on the device. ksack->createMemObjects(&logfile); //7. Create Kernels ksack->createKernel(); //8. Provide arguments for the kernels. // ksack.createKernel(); //9. Submit the kernels to the command queue for execution. //10. Copy the results from the device to the host //ksack.executeMemObjects(); ksack->executeComputation(i, &logfile, local_threads[k]); ksack->printResults(&logfile); } delete ksack; delete test; } } logfile.close(); //http://stackoverflow.com/questions/14063791/double-free-or-corruption-but-why ch.stopChrono(); tm.stop(); cout << "CHRONO TIME: " << ch.getTimeChrono() << endl; cout << "TIMER TIME: " << tm.getTime(); return 0; }
TEST(Test1, pngWriteDataToMemory) { std::cout << "########## Image memory write" << std::endl; PngReader pngReaderFromFile; FilePngInputStream filePngInputStream(IMAGE1); pngReaderFromFile.readFromInputstream(filePngInputStream); Chrono chrono; PngData pngData(pngReaderFromFile.getWidth(), pngReaderFromFile.getHeight(), pngReaderFromFile.getBitDepth(), pngReaderFromFile.getColorType(), pngReaderFromFile.getPixelDataRowPointers()); PngWriter writer(pngData); MemoryPngOutputStream memOs; writer.writePngToOutputStream(memOs); std::cout << "Image write png to memory in " << chrono.elapsedTimeInMs() << " ms, nrOfBytes=" << memOs.getNrOfBytes() << std::endl; // Read the data written to memory, and check against the original MemoryPngInputStream memoryInputstream(memOs.getBuffer().data(), memOs.getNrOfBytes()); PngReader pngReaderFromMemory; pngReaderFromMemory.readFromInputstream(memoryInputstream); AssertUtil::equals(pngReaderFromFile, pngReaderFromMemory); }
int main(void){ Chrono c; c.start(); int sum = 1, step = 2, diagonalcount = 0, previousdiagonal = 1, dimension = 1001; while(previousdiagonal < (dimension * dimension)){ if(diagonalcount == 4){ diagonalcount = 0; step += 2; } int to_add = previousdiagonal + step; sum += to_add; previousdiagonal = to_add; diagonalcount++; } c.stop(); std::cout << "The sum of the numbers on the diagonals in a " << dimension << " by " << dimension << " spiral is " << sum << std::endl; std::cout << "Found the answer in " << c.time() << " seconds" << std::endl; return 0; }
TEST(Test1, pngWriteDataToMemoryDefaultAndPrealloc) { std::cout << "########## Image memory write" << std::endl; PngReader pngReaderFromFile; FilePngInputStream filePngInputStream(IMAGE1); pngReaderFromFile.readFromInputstream(filePngInputStream); Chrono chrono; PngData pngData(pngReaderFromFile.getWidth(), pngReaderFromFile.getHeight(), pngReaderFromFile.getBitDepth(), pngReaderFromFile.getColorType(), pngReaderFromFile.getPixelDataRowPointers()); std::cout << "Number of bytes pixelData=" << pngData.getNrOfBytesPixelData() << std::endl; MemoryPngOutputStream memOs1; { PngWriter writer(pngData); writer.writePngToOutputStream(memOs1); std::cout << "Image write png to memory (no pre-alloc) in " << chrono.elapsedTimeInMs() << " ms, nrOfBytes=" << memOs1.getNrOfBytes() << std::endl; } { PngWriter writer(pngData); const uint32_t estimatedPngHeaderSize= 512; uint32_t outputBufferSize = pngData.getNrOfBytesPixelData() + estimatedPngHeaderSize; MemoryPngOutputStream memOs2(outputBufferSize); writer.writePngToOutputStream(memOs2); std::cout << "Image write png to memory (pre-alloc) in " << chrono.elapsedTimeInMs() << " ms, nrOfBytes=" << memOs2.getNrOfBytes() << std::endl; EXPECT_EQ(memOs1.getNrOfBytes(), memOs2.getNrOfBytes()); } }
void test_with_ctor() { double msecs = 0.0; int c = 0; for (; c<10000; ++c) { Chrono chrono; std::sin(0.0); msecs += chrono.elapsed(); } std::cout << "sin(0) in " << (msecs/c) << " milliseconds (average from " << c << " runs)\n"; }
void Game::update() { Chrono updateTiming; m_state.update(); m_view.setCenter((m_state.getObjects().getPlayer().getPosition())/VIEW_DELAY_FACTOR); m_userInterface.update(m_state); m_userInterface.setUpdateTime(updateTiming.get()); }
double sorteertijd(vector<T> &v, SorteerMethode<T>* methode, int ncycli=1){ double somTijden = 0.0; for (int i = 0; i < ncycli; i++){ vector<T> kopie (v); Chrono c; c.start(); (*methode)(kopie); c.stop(); somTijden += c.tijd(); } return somTijden / ncycli; }
int main(int argc, char **argv) { if (argc < 2) { std::cout << "Usage: pgn-app png-in" << std::endl; return 1; } Chrono chrono; chrono.reset(); IOUtils png; png.readFile(argv[1]); MemoryPngInputStream memoryInputstream((const png_bytep) png.getBuffer(), (const png_size_t) png.getLength()); std::cout << "Image read info memory in " << chrono.elapsedTimeInMs() << " ms" << std::endl; { chrono.reset(); PngReader rdrMem; memoryInputstream.reset(); rdrMem.readFromInputstream(memoryInputstream, true); std::cout << "Image read memory (own alloc)in " << chrono.elapsedTimeInMs() << " ms" << std::endl; } chrono.reset(); PngReader rdrMem; memoryInputstream.reset(); rdrMem.readFromInputstream(memoryInputstream); std::cout << "Image read memory (pnglib alloc) in " << chrono.elapsedTimeInMs() << " ms" << std::endl; PngData pngData(rdrMem.getWidth(), rdrMem.getHeight(), rdrMem.getBitDepth(), rdrMem.getColorType(), rdrMem.getPixelDataRowPointers()); std::cout << "Nr of bytes pixelData=" << pngData.getNrOfBytesPixelData() << std::endl; // Loop to see if having a preallocated buffer works better. Answer: yes // Saving was 0-20 ms (on VM on Laptop: (windows7,[email protected] ghz, 8gb) const uint32_t estimatedPngHeaderSize = 1024 * 8; for (int j = 0; j < 10; j++) { for (uint32_t i = 0; i < 2; i++) { uint32_t outputBufferSize = pngData.getNrOfBytesPixelData() + estimatedPngHeaderSize; MemoryPngOutputStream memOs(i * outputBufferSize); chrono.reset(); PngWriter writer(pngData); writer.writePngToOutputStream(memOs); std::cout << "Iteration: " << i << ", image write png to memory in " << chrono.elapsedTimeInMs() << " ms and has size " << memOs.getNrOfBytes() << " bytes" << std::endl; } } return 0; }
void handle(HttpResponse* const response) { if (chrono.isRunning()) { cout << chrono.remain() << " [" << response->get_code() << "] "; HttpResponseHndl *resp = new HttpResponseHndl(); resp->setTarget(target); client->fetch(target.host, target.port, target.meth, target.resource, target.data, resp); cout << "injected!" << endl; } else { cout << counter-- << " [" << response->get_code() << "] "; } cout << response->get_body().size() << " bytes" << endl; if (counter == 0 || chrono.end()) exit(1); }
void MyGLWindow::InitModels() { Chrono chrono; // load models ModelLoader modelLoader; chrono.start(); _actorLib["Tank"] = modelLoader.LoadFromFile("./data/model/stankbot/models/stankbot.dae"); _actorLib["Tank"]->SetShaderProgram(_shaderProgLib["defaultShader"]); std::cout << "Load stankbot (ms) : " << chrono.ellapsed() << std::endl; chrono.start(); _actorLib["Dragon"] = modelLoader.LoadFromFile("./data/model/dragon_vrip_res3.ply"); _actorLib["Dragon"]->SetShaderProgram(_shaderProgLib["defaultShader"]); std::cout << "Load dragon (ms) : " << chrono.ellapsed() << std::endl; }
void Game::render() { Chrono drawTiming; m_targetWindow.clear(sf::Color::Black); m_targetWindow.setView(m_view); m_state.getObjects().draw(m_targetWindow); m_state.getBorders().draw(m_targetWindow); m_targetWindow.setView(m_targetWindow.getDefaultView()); m_userInterface.draw(m_targetWindow); m_targetWindow.display(); m_userInterface.setDrawTime(drawTiming.get()); }
TEST(Test1, pngReadsFromFileMemoryAllocatedByLibPng) { std::cout << "########## Image file read (using high-level PNG API) via inputstream; memory allocated by LibPng" << std::endl; Chrono chrono; PngReader pngReader; FilePngInputStream filePngInputStream(IMAGE1); pngReader.readFromInputstream(filePngInputStream); std::cout << "Image read from input stream in " << chrono.elapsedTimeInMs() << " ms" << std::endl; EXPECT_EQ(8, pngReader.getBitDepth()); EXPECT_EQ(COLORTYPE_RGB, pngReader.getColorType()); // const size_t expectedNrOfBytes = pngReader.getWidth() * 3 /*rgb*/ * 1 /* # bytes/color*/; EXPECT_EQ(expectedNrOfBytes, pngReader.getNrOfBytesPerRow()); }
int main(int argc, char *argv[]) { srand(time(0)); Sortvector<int> temp(10); temp.shuffle(); //Start het hele sorteer-circus Chrono chr; cout<<"Insertion sort"<<endl; vector<int> vec1 = temp; InsertionSort<int> ins_sort; chr.start(); ins_sort(vec1); chr.stop(); cout<<"Insertion sort duurde "<<chr.tijd()<<"."<<endl; cout<<"STL sort"<<endl; vec1 = temp; STLSort<int> stl_sort; chr.start(); stl_sort(vec1); chr.stop(); cout<<"Insertion sort duurde "<<chr.tijd()<<"."<<endl; return 0; }
void ClientInterface::waitForMessage(){ Chrono chrono; chrono.start(); while(getNextMessageType()==nmtInvalid){ if(!isConnected()){ throw runtime_error("Disconnected"); } if(chrono.getMillis()>messageWaitTimeout){ throw runtime_error("Timeout waiting for message"); } sleep(waitSleepTime); } }
void ClientInterface::waitUntilReady(Checksum* checksum){ NetworkMessageReady networkMessageReady; Chrono chrono; chrono.start(); //send ready message sendMessage(&networkMessageReady); //wait until we get a ready message from the server while(true){ NetworkMessageType networkMessageType= getNextMessageType(); if(networkMessageType==nmtReady){ if(receiveMessage(&networkMessageReady)){ break; } } else if(networkMessageType==nmtInvalid){ if(chrono.getMillis()>readyWaitTimeout){ throw runtime_error("Timeout waiting for server"); } } else{ throw runtime_error("Unexpected network message: " + intToStr(networkMessageType) ); } // sleep a bit sleep(waitSleepTime); } //check checksum if(Config::getInstance().getBool("NetworkConsistencyChecks")){ if(networkMessageReady.getChecksum()!=checksum->getSum()){ throw runtime_error("Checksum error, you don't have the same data as the server"); } } //delay the start a bit, so clients have nore room to get messages sleep(GameConstants::networkExtraLatency); }
TEST(Test1, pngReadsFromFileMemoryAllocatedByPngReader) { std::cout << "########## Image file read (using high-level PNG API) via inputstream; memory allocated by PngReader" << std::endl; Chrono chrono; IOUtils ioUtuls; ioUtuls.readFile(IMAGE1); MemoryPngInputStream memoryInputstream( (const png_bytep) ioUtuls.getBuffer(), (const png_size_t) ioUtuls.getLength()); std::cout << "Image read info memory in " << chrono.elapsedTimeInMs() << " ms" << std::endl; chrono.reset(); PngReader pngReader1; { pngReader1.readFromInputstream(memoryInputstream); std::cout << "Image read from input stream in " << chrono.elapsedTimeInMs() << " ms" << std::endl; } chrono.reset(); PngReader pngReader2; { memoryInputstream.reset(); pngReader2.readFromInputstream(memoryInputstream, true); std::cout << "Image read from input stream in " << chrono.elapsedTimeInMs() << " ms" << std::endl; } AssertUtil::equals(pngReader1, pngReader2); }
int main(int argc, char **argv) { struct Target target; int op, timeout=-1; while ((op = getopt(argc, argv, "h:p:m:r:c:d:t:")) != EOF) { switch(op) { case 'h': target.host = optarg; break; case 'p': target.port = atoi(optarg); break; case 'm': target.meth = optarg; break; case 'r': target.resource = optarg; break; case 'd': target.data = optarg; break; case 'c': counter = atoi(optarg); break; case 't': timeout = atoi(optarg); break; case '?': usage(); break; default: usage(); break; } } if (target.host == NULL || target.meth == NULL || target.port == 0 || target.resource == NULL) usage(); if (counter == -1 && timeout == -1) usage(); cout << "preparing attack ..." << endl; client = new AsyncHttpClient(); try { if (timeout > 0) { chrono.start(timeout); HttpResponseHndl *resp = new HttpResponseHndl(); resp->setTarget(target); client->fetch(target.host, target.port, target.meth, target.resource, target.data, resp); } else { for (float i = 0; i < counter; i++) client->fetch(target.host, target.port, target.meth, target.resource, target.data, new HttpResponseHndl); } } catch(runtime_error e) { cout << "Connection refused." << endl; } cout << "Attacking." << endl; IOLoop::instance()->start(); delete client; }
TEST(Test1, pngReadsFromMemory) { std::cout << "########## Image memory read" << std::endl; Chrono chrono; IOUtils ioUtuls; ioUtuls.readFile(IMAGE1); MemoryPngInputStream memoryInputstream( (const png_bytep) ioUtuls.getBuffer(), (const png_size_t) ioUtuls.getLength()); std::cout << "Image read info memory in " << chrono.elapsedTimeInMs() << " ms" << std::endl; chrono.reset(); PngReader pngReaderFromMemory; pngReaderFromMemory.readFromInputstream(memoryInputstream); std::cout << "Image read memory in " << chrono.elapsedTimeInMs() << " ms" << std::endl; // Now compare that the data read first in memory produces the same result PngReader pngReaderFromFile; FilePngInputStream filePngInputStream(IMAGE1); pngReaderFromFile.readFromInputstream(filePngInputStream); AssertUtil::equals(pngReaderFromFile, pngReaderFromMemory); }
int main(int argc, char **argv) { Random rand; // default constructor seeds with 0 fixed fixed_numbers[NUM_TRIALS]; fixed fixed_roots[NUM_TRIALS]; float float_numbers[NUM_TRIALS]; float float_roots[NUM_TRIALS]; for (int i=0; i < NUM_TRIALS; ++i) { fixed_numbers[i] = rand.randRange(4, 4000); fixed_numbers[i] += rand.randRange(0, 4095) / fixed(4096); float_numbers[i] = fixed_numbers[i].toFloat(); } { // using floats and sqrtf(), for reference Chrono chrono; chrono.start(); for (int i=0; i < NUM_TRIALS; ++i) { float_roots[i] = sqrtf(float_numbers[i]); } chrono.stop(); cout << "\nDone, " << NUM_TRIALS << " floating point square roots. Took " << chrono.getMicros() << "us"; } DO_TEST(sqRt_c); DO_TEST(sqRt_unrolled_once); DO_TEST(sqRt_unrolled_twice); DO_TEST(sqRt_unrolled_thrice); DO_TEST(sqRt_unrolled_completely); DO_TEST(sqRt_julery); DO_TEST(sqRt_julery_crowne); cout << "\n\n[Enter]"; char boo[8]; std::cin.getline(boo, 8); }
void xPLCron::SetValue(Chrono& chrono, const string& value) { xPL::SchemaControlBasic sendCmnd; string moduleName; string deviceName; string deviceType; LOG_ENTER; moduleName = chrono.GetModuleName(); deviceName = chrono.GetDeviceName(); deviceType = chrono.GetDeviceType(); chrono.SetValue(value); sendCmnd.SetDeviceType(deviceType); sendCmnd.SetDeviceName(deviceName); sendCmnd.SetCurrent(value); LOG_VERBOSE(m_Log) << "Send " << value << " to " << moduleName << " device " << deviceName; m_xPLDevice.SendMessage(&sendCmnd, moduleName); LOG_EXIT_OK; }
void launch_bench_square(Field & F // const problem , size_t min, size_t max, size_t step // no negative step , PlotData & Data ) { linbox_check(step); linbox_check(min <= max); std::ostringstream nam ; F.write(nam); // Data.setCurrentSeriesName(nam.str()); Data.newSeries(nam.str()); Chrono<Timer> TW ; typedef typename Field::RandIter Randiter ; Randiter R(F) ; BlasMatrixDomain<Field> BMD(F) ; RandomDenseMatrix<Randiter,Field> RandMat(F,R); for ( size_t i = min ; i < max ; i += step ) { showAdvanceLinear(i,min,max); size_t ii = i ; BlasMatrix<Field> A (F,ii,ii); BlasMatrix<Field> B (F,ii,ii); BlasMatrix<Field> C (F,ii,ii); size_t j = 0 ; // number of repets. RandMat.random(A); RandMat.random(B); RandMat.random(C); TW.clear() ; while( Data.keepon(j,TW.time(),false) ) { TW.start() ; BMD.mul(C,A,B) ; // C = AB TW.stop(); ++j ; } double mflops = computeMFLOPS(TW.times(),mm_mflops(i,i,i)); Data.setCurrentSeriesEntry(i,mflops,(double)i,TW.time()); // could be i*i*i } Data.finishSeries(); }
void android_main(struct android_app* state) { app_dummy(); //sleep(5); // Sleep a little so GDB can attach itself pthread_key_create(&s_thread_key, detach_current_thread); JNIEnv* env; state->activity->vm->AttachCurrentThread(&env, nullptr); pthread_setspecific(s_thread_key, state->activity->vm); AInstance ainstance; state->userData = &ainstance; state->onAppCmd = android_handle_event; state->onInputEvent = android_handle_input; ainstance.app = state; g_native_activity = state->activity; Path::set_current(); // Prepare to monitor accelerometer ainstance.sensorManager = ASensorManager_getInstance(); ainstance.accelerometerSensor = ASensorManager_getDefaultSensor( ainstance.sensorManager, ASENSOR_TYPE_ACCELEROMETER); if (ainstance.accelerometerSensor) { ainstance.sensorEventQueue = ASensorManager_createEventQueue( ainstance.sensorManager, state->looper, LOOPER_ID_USER, nullptr, nullptr); } Chrono chrono; while (!ainstance.done) { int ident; int events; struct android_poll_source* source; while ((ident = ALooper_pollAll( (!ainstance.active ? -1 : 0), nullptr, &events, reinterpret_cast<void**>(&source))) >= 0) { if (source) source->process(state, source); if (ainstance.done) break; // If a sensor has data, process it now. if (ainstance.active && ident == LOOPER_ID_USER && ainstance.accelerometerSensor) { ASensorEvent event; while (ASensorEventQueue_getEvents( ainstance.sensorEventQueue, &event, 1) > 0) { ainstance.director->input().accelerated( event.acceleration.x, event.acceleration.y, event.acceleration.z, event.timestamp); } } } chrono.update(); if (!(ainstance.initialised & ainstance.active)) continue; ainstance.director->update(chrono.delta()); ainstance.director->draw(); eglSwapBuffers(ainstance.display, ainstance.surface); } android_destroy_display(&ainstance); }
void launch_bench_rank(const Field &F, const std::string & name , PlotData & Data ) { SparseMatrix<Field> Mat(F); std::ifstream mat1 (name); Mat.read(mat1); MatrixMetaData mmd (Mat,name); // Data.newSeries(name); Chrono<Timer> TW ; showAdvanceLinear(1,1,2); TW.clear() ; size_t j = 0 ; while( Data.keepon(j,TW.time()) ) { TW.start() ; unsigned long d ; LinBox::rank(d,Mat,Method::Blackbox()); TW.stop(); ++j ; } // double mflops = computeMFLOPS(TW.times(),mm_mflops(i,i,i)); Data.setSeriesEntry("Rank (Blackbox)",name,TW.time(),(double)Mat.size(),TW.time()); Data.addCurrentEntryMetaData(mmd); // Data.addCurrentSeriesMetaData(mmd); // Data.addMetaData(mmd); showAdvanceLinear(2,1,2); TW.clear() ; j = 0 ; while( Data.keepon(j,TW.time()) ) { TW.start() ; unsigned long d ; LinBox::rank(d,Mat,Method::SparseElimination()); TW.stop(); ++j ; } Data.selectSeries("Rank (SparseElimination)"); Data.setCurrentSeriesEntry(name,TW.time(),(double)Mat.size(),TW.time()); Data.addCurrentEntryMetaData(mmd); }
int recollq(RclConfig **cfp, int argc, char **argv) { string a_config; string sortfield; string stemlang("english"); list<string> extra_dbs; string sf; vector<string> fields; int firstres = 0; int maxcount = 2000; thisprog = argv[0]; argc--; argv++; while (argc > 0 && **argv == '-') { (*argv)++; if (!(**argv)) /* Cas du "adb - core" */ Usage(); while (**argv) switch (*(*argv)++) { case '-': // -- : end of options if (*(*argv) != 0) Usage(); goto endopts; case 'A': op_flags |= OPT_A; break; case 'a': op_flags |= OPT_a; break; case 'b': op_flags |= OPT_b; break; case 'c': op_flags |= OPT_c; if (argc < 2) Usage(); a_config = *(++argv); argc--; goto b1; case 'd': op_flags |= OPT_d; break; case 'D': op_flags |= OPT_D; break; case 'e': op_flags |= OPT_e; break; case 'f': op_flags |= OPT_f; break; case 'F': op_flags |= OPT_F; if (argc < 2) Usage(); sf = *(++argv); argc--; goto b1; case 'i': op_flags |= OPT_i; if (argc < 2) Usage(); extra_dbs.push_back(*(++argv)); argc--; goto b1; case 'l': op_flags |= OPT_l; break; case 'm': op_flags |= OPT_m; break; case 'N': op_flags |= OPT_N; break; case 'n': op_flags |= OPT_n; if (argc < 2) Usage(); { string rescnt = *(++argv); string::size_type dash = rescnt.find("-"); if (dash != string::npos) { firstres = atoi(rescnt.substr(0, dash).c_str()); if (dash < rescnt.size()-1) { maxcount = atoi(rescnt.substr(dash+1).c_str()); } } else { maxcount = atoi(rescnt.c_str()); } if (maxcount <= 0) maxcount = INT_MAX; } argc--; goto b1; case 'o': op_flags |= OPT_o; break; case 'P': op_flags |= OPT_P; break; case 'q': op_flags |= OPT_q; break; case 'Q': op_flags |= OPT_Q; break; case 'S': op_flags |= OPT_S; if (argc < 2) Usage(); sortfield = *(++argv); argc--; goto b1; case 's': op_flags |= OPT_s; if (argc < 2) Usage(); stemlang = *(++argv); argc--; goto b1; case 't': op_flags |= OPT_t; break; default: Usage(); break; } b1: argc--; argv++; } endopts: string reason; *cfp = recollinit(0, 0, reason, &a_config); RclConfig *rclconfig = *cfp; if (!rclconfig || !rclconfig->ok()) { fprintf(stderr, "Recoll init failed: %s\n", reason.c_str()); exit(1); } if (argc < 1 && !(op_flags & OPT_P)) { Usage(); } if (op_flags & OPT_F) { if (op_flags & (OPT_b|OPT_d|OPT_b|OPT_Q|OPT_m|OPT_A)) Usage(); stringToStrings(sf, fields); } Rcl::Db rcldb(rclconfig); if (!extra_dbs.empty()) { for (list<string>::iterator it = extra_dbs.begin(); it != extra_dbs.end(); it++) { if (!rcldb.addQueryDb(*it)) { cerr << "Can't add index: " << *it << endl; exit(1); } } } if (!rcldb.open(Rcl::Db::DbRO)) { cerr << "Cant open database in " << rclconfig->getDbDir() << " reason: " << rcldb.getReason() << endl; exit(1); } if (op_flags & OPT_P) { int minyear, maxyear; if (!rcldb.maxYearSpan(&minyear, &maxyear)) { cerr << "maxYearSpan failed: " << rcldb.getReason() << endl; exit(1); } else { cout << "Min year " << minyear << " Max year " << maxyear << endl; exit(0); } } if (argc < 1) { Usage(); } string qs = *argv++;argc--; while (argc > 0) { qs += string(" ") + *argv++;argc--; } { string uq; string charset = rclconfig->getDefCharset(true); int ercnt; if (!transcode(qs, uq, charset, "UTF-8", &ercnt)) { fprintf(stderr, "Can't convert command line args to utf-8\n"); exit(1); } else if (ercnt) { fprintf(stderr, "%d errors while converting arguments from %s " "to utf-8\n", ercnt, charset.c_str()); } qs = uq; } Rcl::SearchData *sd = 0; if (op_flags & (OPT_a|OPT_o|OPT_f)) { sd = new Rcl::SearchData(Rcl::SCLT_OR, stemlang); Rcl::SearchDataClause *clp = 0; if (op_flags & OPT_f) { clp = new Rcl::SearchDataClauseFilename(qs); } else { clp = new Rcl::SearchDataClauseSimple((op_flags & OPT_o)? Rcl::SCLT_OR : Rcl::SCLT_AND, qs); } if (sd) sd->addClause(clp); } else { sd = wasaStringToRcl(rclconfig, stemlang, qs, reason); } if (!sd) { cerr << "Query string interpretation failed: " << reason << endl; return 1; } RefCntr<Rcl::SearchData> rq(sd); Rcl::Query query(&rcldb); if (op_flags & OPT_S) { query.setSortBy(sortfield, (op_flags & OPT_D) ? false : true); } Chrono chron; if (!query.setQuery(rq)) { cerr << "Query setup failed: " << query.getReason() << endl; return(1); } int cnt = query.getResCnt(); if (!(op_flags & OPT_b)) { cout << "Recoll query: " << rq->getDescription() << endl; if (firstres == 0) { if (cnt <= maxcount) cout << cnt << " results" << endl; else cout << cnt << " results (printing " << maxcount << " max):" << endl; } else { cout << "Printing at most " << cnt - (firstres+maxcount) << " results from first " << firstres << endl; } } if (op_flags & OPT_Q) cout << "Query setup took " << chron.millis() << " mS" << endl; if (op_flags & OPT_Q) return(0); for (int i = firstres; i < firstres + maxcount; i++) { Rcl::Doc doc; if (!query.getDoc(i, doc)) break; if (op_flags & OPT_F) { output_fields(fields, doc, query, rcldb, op_flags & OPT_N); continue; } if (op_flags & OPT_e) doc.url = url_encode(doc.url); if (op_flags & OPT_b) { cout << doc.url << endl; } else { string titleorfn = doc.meta[Rcl::Doc::keytt]; if (titleorfn.empty()) titleorfn = doc.meta[Rcl::Doc::keyfn]; if (titleorfn.empty()) { string url; printableUrl(rclconfig->getDefCharset(), doc.url, url); titleorfn = path_getsimple(url); } char cpc[20]; sprintf(cpc, "%d", doc.pc); cout << doc.mimetype << "\t" << "[" << doc.url << "]" << "\t" << "[" << titleorfn << "]" << "\t" << doc.fbytes << "\tbytes" << "\t" << endl; if (op_flags & OPT_m) { for (map<string,string>::const_iterator it = doc.meta.begin(); it != doc.meta.end(); it++) { cout << it->first << " = " << it->second << endl; } } if (op_flags & OPT_A) { string abstract; if (query.makeDocAbstract(doc, abstract)) { cout << "ABSTRACT" << endl; cout << abstract << endl; cout << "/ABSTRACT" << endl; } } } if (op_flags & OPT_d) { dump_contents(rclconfig, doc); } } return 0; }
/** * @brief Less operator. */ inline bool operator<( const Chrono& other ) const { return ( elapsedMicroSeconds() < other.elapsedMicroSeconds() ); }
//-*** Exported Functions : infinitise() void infinitise(void ***Zprim, REELLE **Zbuf, double cste_dist,int** roof,int Tx, int Ty,bool dupli) { int i,j; if(verbose>1){ myclock.Start(); cout<<"* infinitise(): DEBUT\n"; } //init Zdat0.alloue(Tx,Ty); Zbuf0.alloue(Tx,Ty); // parameters --> global variables Zdat8=Zprim; Zbuf8=Zbuf; T=roof; duplik=dupli; cdist=cste_dist; Ti=Tx;Tj=Ty; for(j=0;j<Ty;j++) for(i=0;i<Tx;i++) { Zdat0(i,j)=Zprim[i][j]; Zbuf0(i,j)=Zbuf[i][j]; } i=j=0; /* for(int ii=0; ii<4; ii++) for(int jj=0;jj<2;jj++) printf("----> T(%d,%d) = %d\n",ii,jj,T[ii][jj]); */ /* //MC 1996 : Ok mais pb d'arrondi possible donc... tr[0]=T[3][0]-T[0][0]; tr[1]=T[3][1]-T[0][1]; tr[2]=T[1][0]-T[0][0]; tr[3]=T[1][1]-T[0][1]; */ // printf("\nOLD tr(0-3)=(%d, %d, %d, %d)\n", tr[0], tr[1], tr[2], tr[3]); //MC09: debug / fort angles zenitaux => ne chga erien mais plus rigoureux tr[0]=round( ( (T[3][0]-T[0][0]) +(T[2][0]-T[1][0]) )/2.); tr[1]=round( ( (T[3][1]-T[0][1]) +(T[2][1]-T[1][1]) )/2.); tr[2]=round( ( (T[1][0]-T[0][0]) +(T[2][0]-T[3][0]) )/2.); tr[3]=round( ( (T[1][1]-T[0][1]) +(T[2][1]-T[3][1]) )/2.); //fin dbug MC09 tr[4]=-tr[2]; tr[5]=-tr[3]; tr[6]=-tr[0]; tr[7]=-tr[1]; // printf(" NEW tr(0-3)=(%d, %d, %d, %d)\n", tr[0], tr[1], tr[2], tr[3]); // pave tq le toit et ses translates pavent tte l'image pave(i,j,0); //up i+=tr[6]; j+=tr[7]; pave(i,j,6); //down //Mr Propre Zdat0.free(); Zbuf0.free(); if(verbose>1){ myclock.Stop(); cout<<"\n::::> Infinitisation en "<<myclock<<endl; fflush(stdout); } }//infinitise()
int main(int argc, char** argv) { // Sets a random seed for each run of FFAST. srand48((long int) time (NULL)); // Configurations are set through the command line arguments Config* configurations = new Config(argc, argv); // This is here measuring how long it takes to generate the input and output // and FFTW if it is asked Chrono* mChrono = new Chrono(); // Input object Input* input; // Output object Output* output; // In the experiment mode, program uses randomly generated input and // compare the FFAST output to the input. // In the customized mode, program takes input from a file and outputs // the recovered signal to a file. // Note that input and output to FFAST is made modular and for using FFAST // in other applications changing these objects would be enough. if ( configurations->isExperimentMode() ) { input = new ExperimentInput(mChrono, configurations); // output = new CustomizedOutput(mChrono, configurations); output = new ExperimentOutput(mChrono, configurations, dynamic_cast<ExperimentInput*>(input)); } else { input = new CustomizedInput(mChrono, configurations); output = new CustomizedOutput(mChrono, configurations); } FFAST* ffast = new FFAST(configurations, input, output); if (!configurations->isHelpDisplayed()) { // the number of iterations entered by the user int iterations = configurations->getIterations(); configurations->display(); // do the required number of iterations for (int iteration=0; iteration<iterations; iteration++) { input->process( ffast->getDelays() ); ffast->process(); output->process(); } ffast->displayResults(); if ( configurations->isExperimentMode() ) { std::cout << std::setprecision(3) << std::scientific << mChrono->average("Input") << " -> signal generation time" << std::endl; } } if (configurations->needToCompareWithFFTW()) { input->process(); const std::unordered_map<int,ffast_complex> mymap = input->getTimeSignal(); ffast_complex* inputSignal = (ffast_complex*) fftw_malloc(configurations->getSignalLength() * sizeof(ffast_complex)); for ( auto it = mymap.begin(); it!= mymap.end(); ++it ) { inputSignal[it->first] = it->second; } FFTW* fftw = new FFTW(mChrono, configurations, inputSignal); fftw->process(); std::cout << std::endl; std::cout << "<===== FFTW =====>" << std::endl; std::cout << std::setprecision(3) << std::scientific << mChrono->average("FFTW") << " -> execution of FFTW" << std::endl; delete fftw; } std::cout << std::endl; delete ffast; exit(EXIT_SUCCESS); }
// Fix result text for display inside the gui text window. // // We call overridden functions to output header data, beginnings and ends of // matches etc. // // If the input is text, we output the result in chunks, arranging not // to cut in the middle of a tag, which would confuse qtextedit. If // the input is html, the body is always a single output chunk. bool PlainToRich::plaintorich(const string& in, list<string>& out, // Output chunk list const HighlightData& hdata, int chunksize) { Chrono chron; bool ret = true; LOGDEB1(("plaintorichich: in: [%s]\n", in.c_str())); m_hdata = &hdata; // Compute the positions for the query terms. We use the text // splitter to break the text into words, and compare the words to // the search terms, TextSplitPTR splitter(hdata); // Note: the splitter returns the term locations in byte, not // character, offsets. splitter.text_to_words(in); LOGDEB2(("plaintorich: split done %d mS\n", chron.millis())); // Compute the positions for NEAR and PHRASE groups. splitter.matchGroups(); LOGDEB2(("plaintorich: group match done %d mS\n", chron.millis())); out.clear(); out.push_back(""); list<string>::iterator olit = out.begin(); // Rich text output *olit = header(); // No term matches. Happens, for example on a snippet selected for // a term match when we are actually looking for a group match // (the snippet generator does this...). if (splitter.tboffs.empty()) { LOGDEB1(("plaintorich: no term matches\n")); ret = false; } // Iterator for the list of input term positions. We use it to // output highlight tags and to compute term positions in the // output text vector<MatchEntry>::iterator tPosIt = splitter.tboffs.begin(); vector<MatchEntry>::iterator tPosEnd = splitter.tboffs.end(); #if 0 for (vector<pair<int, int> >::const_iterator it = splitter.tboffs.begin(); it != splitter.tboffs.end(); it++) { LOGDEB2(("plaintorich: region: %d %d\n", it->first, it->second)); } #endif // Input character iterator Utf8Iter chariter(in); // State variables used to limit the number of consecutive empty lines, // convert all eol to '\n', and preserve some indentation int eol = 0; int hadcr = 0; int inindent = 1; // HTML state bool intag = false, inparamvalue = false; // My tag state int inrcltag = 0; string::size_type headend = 0; if (m_inputhtml) { headend = in.find("</head>"); if (headend == string::npos) headend = in.find("</HEAD>"); if (headend != string::npos) headend += 7; } for (string::size_type pos = 0; pos != string::npos; pos = chariter++) { // Check from time to time if we need to stop if ((pos & 0xfff) == 0) { CancelCheck::instance().checkCancel(); } // If we still have terms positions, check (byte) position. If // we are at or after a term match, mark. if (tPosIt != tPosEnd) { int ibyteidx = chariter.getBpos(); if (ibyteidx == tPosIt->offs.first) { if (!intag && ibyteidx >= (int)headend) { *olit += startMatch(tPosIt->grpidx); } inrcltag = 1; } else if (ibyteidx == tPosIt->offs.second) { // Output end of match region tags if (!intag && ibyteidx > (int)headend) { *olit += endMatch(); } // Skip all highlight areas that would overlap this one int crend = tPosIt->offs.second; while (tPosIt != splitter.tboffs.end() && tPosIt->offs.first < crend) tPosIt++; inrcltag = 0; } } unsigned int car = *chariter; if (car == '\n') { if (!hadcr) eol++; hadcr = 0; continue; } else if (car == '\r') { hadcr++; eol++; continue; } else if (eol) { // Got non eol char in line break state. Do line break; inindent = 1; hadcr = 0; if (eol > 2) eol = 2; while (eol) { if (!m_inputhtml && m_eolbr) *olit += "<br>"; *olit += "\n"; eol--; } // Maybe end this chunk, begin next. Don't do it on html // there is just no way to do it right (qtextedit cant grok // chunks cut in the middle of <a></a> for example). if (!m_inputhtml && !inrcltag && olit->size() > (unsigned int)chunksize) { out.push_back(string(startChunk())); olit++; } } switch (car) { case '<': inindent = 0; if (m_inputhtml) { if (!inparamvalue) intag = true; chariter.appendchartostring(*olit); } else { *olit += "<"; } break; case '>': inindent = 0; if (m_inputhtml) { if (!inparamvalue) intag = false; } chariter.appendchartostring(*olit); break; case '&': inindent = 0; if (m_inputhtml) { chariter.appendchartostring(*olit); } else { *olit += "&"; } break; case '"': inindent = 0; if (m_inputhtml && intag) { inparamvalue = !inparamvalue; } chariter.appendchartostring(*olit); break; case ' ': if (m_eolbr && inindent) { *olit += " "; } else { chariter.appendchartostring(*olit); } break; case '\t': if (m_eolbr && inindent) { *olit += " "; } else { chariter.appendchartostring(*olit); } break; default: inindent = 0; chariter.appendchartostring(*olit); } } // End chariter loop #if 0 { FILE *fp = fopen("/tmp/debugplaintorich", "a"); fprintf(fp, "BEGINOFPLAINTORICHOUTPUT\n"); for (list<string>::iterator it = out.begin(); it != out.end(); it++) { fprintf(fp, "BEGINOFPLAINTORICHCHUNK\n"); fprintf(fp, "%s", it->c_str()); fprintf(fp, "ENDOFPLAINTORICHCHUNK\n"); } fprintf(fp, "ENDOFPLAINTORICHOUTPUT\n"); fclose(fp); } #endif LOGDEB2(("plaintorich: done %d mS\n", chron.millis())); return ret; }
void MyGLWindow::InitMCMesh() { // timings Chrono chrono; chrono.start(); // initialize marching cube float minValue = 0; //0.5f; float minX, maxX; float minY, maxY; float minZ, maxZ; minX = minY = minZ = -1.5f; maxX = maxY = maxZ = 1.5f; unsigned int nX, nY, nZ; nX = nY = 200; nZ = 100; // 700, 700, 400 => OK std::vector<glm::vec4> mcPoints((nX + 1) * (nY + 1) * (nZ + 1)); glm::vec3 mcStep((maxX - minX) / nX, (maxY - minY) / nY, (maxZ - minZ) / nZ); PerlinNoise perlin( time(NULL) ); #pragma omp parallel for for(int x = 0; x < nX + 1; ++x) for(int y = 0; y < nY + 1; ++y) for(int z = 0; z < nZ + 1; ++z) { glm::vec4 point( minX + x * mcStep.x, minY + y * mcStep.y, minZ + z * mcStep.z, 0); // test terrain point.w = -point.y; float freq = 11.03f; float amp = 0.25f; float sum = 0.0f; float lacunarity = 0.198f; float gain = 2.0f; unsigned int octaves = 9; for(unsigned int i = 0; i < octaves; ++i) { sum += perlin.Noise(point.x * freq, point.y * freq, point.z * freq) * amp; freq *= lacunarity; amp * gain; } point.w += sum; //point.w = Potential(point.x, point.y, point.z); mcPoints[x * (nY + 1) * (nZ + 1) + y * (nZ + 1) + z] = point; } std::cout << "Initialization timer (ms) : " << chrono.ellapsed() << std::endl; // run marching cube chrono.start(); std::vector<Triangle> mcTriangles; MarchingCube mc; mc.SetMinValue(minValue); mc.SetDimension(nX, nY, nZ); mc.Process(mcPoints, mcTriangles); std::cout << "Marching cube timer (ms) : " << chrono.ellapsed() << std::endl; unsigned int triangleCount = mcTriangles.size(); std::cout << "Point count : " << mcPoints.size() << std::endl; std::cout << "Triangle count : " << triangleCount << std::endl; // initialize data std::vector<float> positionArray; std::vector<float> normalArray; for(auto t : mcTriangles) { for(int i = 0; i < 3; ++i) { positionArray.push_back(t.vertices[i].x); positionArray.push_back(t.vertices[i].y); positionArray.push_back(t.vertices[i].z); normalArray.push_back(t.normal[i].x); normalArray.push_back(t.normal[i].y); normalArray.push_back(t.normal[i].z); } } // create 3D primitive from marching cube MeshT mcMesh(new Mesh); mcMesh->SetBufferData(ShaderLocation::Position, positionArray, 3); mcMesh->SetBufferData(ShaderLocation::Normal, normalArray, 3); mcMesh->SetPrimitiveType(GL_TRIANGLES); _meshLib["MCMesh"] = mcMesh; Material terrainMaterial; terrainMaterial.SetAmbientColor( glm::vec3(0.2f, 0.9f, 0.3f) ); terrainMaterial.SetDiffuseColor( glm::vec3(0.2f, 0.9f, 0.3f) ); terrainMaterial.SetSpecularColor( glm::vec3(0.8f, 0.8f, 0.8f) ); ActorT terrain(new Actor); terrain->AddDrawableMesh(_meshLib["MCMesh"], terrainMaterial); terrain->SetShaderProgram(_shaderProgLib["defaultShader"]); _actorLib["Terrain"] = terrain; }
int main(int argc, char ** argv) { // read command line arguments if (argc != 5) { cerr << "usage: " << argv[0] << " <training samples> <training labels>" << " <testing samples> <testing labels>" << endl; exit(-1); } const string trainingSamplesFilename = argv[1]; const string trainingLabelsFilename = argv[2]; const string testingSamplesFilename = argv[3]; const string testingLabelsFilename = argv[4]; try { Chrono chrono; cout << fixed << showpoint << setprecision(2); ////////////////////////////////////////////////// // training ////////////////////////////////////////////////// int trainingN, trainingQ, trainingK; cv::Mat trainingSamples, trainingLabels; loadSamplesLabels(trainingSamplesFilename, trainingSamples, trainingLabelsFilename, trainingLabels, trainingN, trainingQ, trainingK); // build class probabilities cv::Mat trainingLabelsK = cv::Mat::zeros(trainingN, trainingK, CV_64FC1); cv::Mat trainingHist = cv::Mat::zeros(1, trainingK, CV_32SC1); for (int n=0; n<trainingN; n++) { int r = trainingLabels.at<int>(n, 0); assert(r>=0 and r<trainingK); trainingLabelsK.at<double>(n, r) = 1.0; trainingHist.at<int>(0, r)++; } cout << "trainingHist: " << format(trainingHist, "csv") << endl; // TODO tune network // init layers (2 hidden layers with 10 neurons per layer) cv::Mat layers = cv::Mat(3, 1, CV_32SC1); layers.row(0) = cv::Scalar(trainingQ); layers.row(1) = cv::Scalar(trainingQ*trainingK); layers.row(2) = cv::Scalar(trainingK); CvANN_MLP network; network.create(layers); // init training params CvANN_MLP_TrainParams params; CvTermCriteria criteria; criteria.max_iter = 100; criteria.epsilon = 0.00001f; criteria.type = CV_TERMCRIT_ITER | CV_TERMCRIT_EPS; params.term_crit = criteria; params.train_method = CvANN_MLP_TrainParams::BACKPROP; params.bp_dw_scale = 0.05f; params.bp_moment_scale = 0.05f; // compute training network.train(trainingSamples, trainingLabelsK, cv::Mat(), cv::Mat(), params); double trainingTime = chrono.elapsedAndReset(); cout << "trainingTime: " << trainingTime << endl << endl; ////////////////////////////////////////////////// // testing ////////////////////////////////////////////////// int testingN, testingQ, testingK; cv::Mat testingSamples, testingLabels; loadSamplesLabels(testingSamplesFilename, testingSamples, testingLabelsFilename, testingLabels, testingN, testingQ, testingK); // compute testing int K = max(trainingK, testingK); cv::Mat testingHist = cv::Mat::zeros(1, K, CV_32SC1); cv::Mat positives = cv::Mat::zeros(K, K, CV_32SC1); unsigned nbTp = 0; unsigned nbFp = 0; for(int n = 0; n < testingN; n++) { // compute prediction cv::Mat sample = testingSamples.row(n); // TODO remove allocation ? cv::Mat prediction; network.predict(sample, prediction); //cout << "sample: " << format(sample, "csv") << endl; //cout << "prediction: " << format(prediction, "csv") << endl; // get the class corresponding to the prediction double vMin, vMax; cv::Point pMin, pMax; cv::minMaxLoc(prediction, &vMin, &vMax, &pMin, &pMax); // test if expected == predicted int predicted = pMax.x; int expected = testingLabels.at<int>(n, 0); //cout << "expected: " << expected << endl; //cout << "predicted: " << predicted << endl; testingHist.at<int>(0, expected)++; positives.at<int>(predicted, expected)++; if (expected == predicted) nbTp++; else nbFp++; } cout << "testingHist: " << format(testingHist, "csv") << endl; double accuracy = nbTp / double(nbTp+nbFp); double testingTime = chrono.elapsed(); cout << "testingTime: " << testingTime << endl << endl; ////////////////////////////////////////////////// // display results ////////////////////////////////////////////////// // TODO display network params cout << " " << format(positives,"csv") << endl; cout << "accuracy: " << accuracy << endl; } catch (cv::Exception & e) { cerr << "exception caught: " << e.what() << endl; } return 0; }