void MainWindow::on_action_write_triggered() { QString xlsFile = QFileDialog::getExistingDirectory(this); if(xlsFile.isEmpty()) return; xlsFile += "/excelRWByCztr1988.xls"; QElapsedTimer timer; timer.start(); if(m_xls.isNull()) m_xls.reset(new ExcelBase); m_xls->create(xlsFile); qDebug()<<"create cost:"<<timer.elapsed()<<"ms";timer.restart(); QList< QList<QVariant> > m_datas; for(int i=0;i<1000;++i) { QList<QVariant> rows; for(int j=0;j<100;++j) { rows.append(i*j); } m_datas.append(rows); } m_xls->setCurrentSheet(1); timer.restart(); m_xls->writeCurrentSheet(m_datas); qDebug()<<"write cost:"<<timer.elapsed()<<"ms";timer.restart(); m_xls->save(); }
void DefaultStateChartDriver::onStateChartCycle() { //void m_sc->runCycle(); if (m_sc->getDefaultSCI()->isRaised_heartbeat()) { static QElapsedTimer timer; if (timer.isValid()) qDebug() << "heartbeat :" << timer.elapsed() << "/ 1000"; timer.restart(); } if (m_sc->getDefaultSCI()->isRaised_footstomp()) { static QElapsedTimer timer; if (timer.isValid()) qDebug() << "footstomp :" << timer.elapsed() << "/300"; timer.restart(); } if (m_sc->getDefaultSCI()->isRaised_fingertap()) { static QElapsedTimer timer; if (timer.isValid()) qDebug() << "fingertap :" << timer.elapsed() << "/ 215"; timer.restart(); } if (m_sc->getDefaultSCI()->isRaised_done()) { qDebug() << "done"; QCoreApplication::quit(); } }
void qHashBench() { QElapsedTimer timer; timer.start(); QHash<int,triple> data; triple point; int i; for (i = 0; i < RAND_COUNT; ++i) { point.x = i; point.y = rand(); point.z = rand(); //printf("%d %d %d %d\n", i, point.x, point.y, point.z); data[i] = point; } qDebug() << Q_FUNC_INFO << "creation: elapsed" << timer.elapsed(); timer.restart(); foreach (const triple &t, data) { if (t.x % 1000 == 0) doSomething(t.x); } qDebug() << " foreach: elapsed" << timer.elapsed(); #if QT_VERSION >= 0x050700 timer.restart(); foreach (const triple &t, qAsConst(data)) { if (t.x % 1000 == 0) doSomething(t.x); } qDebug() << " qAsConst foreach: elapsed" << timer.elapsed(); #endif timer.restart(); for( auto it = data.begin(); it != data.end(); ++it ) { if (it->x % 1000 == 0) doSomething(it->x); } qDebug() << " range-based for: elapsed" << timer.elapsed(); #if QT_VERSION >= 0x050700 timer.restart(); for( auto it = qAsConst(data).begin(); it != qAsConst(data).end(); ++it ) { if (it->x % 1000 == 0) doSomething(it->x); } qDebug() << " qAsConst range-based for: elapsed" << timer.elapsed(); #endif timer.restart(); for (i = 0; i < RAND_COUNT; ++i) { auto it = data.find(i); Q_ASSERT(it.value().x == i); if (it->x % 1000 == 0) doSomething(it.value().x); } qDebug() << " find: elapsed" << timer.elapsed(); }
void MainWindow::startCopyFile(QString &path) { if(isPathExcept(path)) return; // 流逝时间计算 static QElapsedTimer et; et.start(); lastSynFileNotify("正在同步: " + path); if(!autoSyn && !click) return; for(auto compareFolder : compareList) { QFileInfo file(path); QDir target(compareFolder); QString newName = target.filePath(file.fileName()); // 获得文件名,构造路径 qDebug() << "newPath: " + newName; // 同步两个文件 synTwoFiles(path,newName); if(et.elapsed() > 300) { QCoreApplication::processEvents(); et.restart(); } lastSynTimeNotify(); } }
void CameraOpenCV::startCapture() { m_videoCap.open(m_devNum); std::cout << "Exposure: " << m_videoCap.get(CV_CAP_PROP_EXPOSURE) << std::endl; m_videoCap.set(CV_CAP_PROP_EXPOSURE, 10); std::cout << "Exposure: " << m_videoCap.get(CV_CAP_PROP_EXPOSURE) << std::endl; capturing = m_videoCap.isOpened(); if (capturing) { cv::Mat frame, out; m_videoCap >> frame; QElapsedTimer timer; timer.start(); m_grabTimeMS = 0; for (int i = 0; i < 30; ++i) { m_videoCap >> frame; m_grabTimeMS += timer.restart(); } m_grabTimeMS /= 30; cout << "Measured grab time: " << m_grabTimeMS << endl; cv::cvtColor(frame, out, cv::COLOR_BGR2GRAY); m_bytes = out.step * out.rows; } }
Q_DECL_EXPORT int main(int argc, char *argv[]) { QScopedPointer<QApplication> app(createApplication(argc, argv)); cv::Mat img, img2, out, out2; img = cvLoadImage("Imagenes/city_night.jpeg"); img2 = cvLoadImage("Imagenes/city_night.jpeg"); out.create(img.size(), img.type()); out2.create(img2.size(), img2.type()); QElapsedTimer timer; qint64 nanoSec, nanoSec2; timer.start(); //Lo hace todo en un solo hilo cv::threshold(img2,out2,66,255,1); nanoSec = timer.nsecsElapsed(); qDebug() << nanoSec; timer.restart(); // create 8 threads and use TBB cv::parallel_for_(cv::Range(0, 8), Parallel_process(img, out, 5, 8)); nanoSec2 = timer.nsecsElapsed(); qDebug() << nanoSec - nanoSec2; cv::imshow("image", out2); cv::imshow("blur", out); return app->exec(); }
void TrendDataCollector::process() { qDebug() << "Starting processing..."; this->setAttribute(this->mAttributeName); QMutexLocker ml(&this->mMutex); this->mStopProcess = false; QElapsedTimer timer; timer.start(); this->updateCurve(); while (this->mStopProcess == false) { ml.relock(); if (this->mPauseProcess == false) { if (timer.hasExpired(this->mInterval)) { ml.unlock(); timer.restart(); this->updateCurve(); } } ml.unlock(); QThread::msleep(10); } emit finished(); }
extern "C" int gitProgressCB(bool reset, const char *text) { static QElapsedTimer timer; static qint64 lastTime; static QString lastText; static QMLManager *self; static int lastPercent; if (!self) self = QMLManager::instance(); if (!timer.isValid() || reset) { timer.restart(); lastTime = 0; lastPercent = 0; lastText.clear(); } if (self) { qint64 elapsed = timer.elapsed(); // don't show the same status twice in 200ms if (lastText == text && elapsed - lastTime < 200) return 0; self->loadDiveProgress(++lastPercent); QString logText = QString::number(elapsed / 1000.0, 'f', 1) + " / " + QString::number((elapsed - lastTime) / 1000.0, 'f', 3) + QString(" : git %1 (%2)").arg(lastPercent).arg(text); self->appendTextToLog(logText); qDebug() << logText; if (elapsed - lastTime > 500) qApp->processEvents(); lastTime = elapsed; } // return 0 so that we don't end the download return 0; }
bool TestLocalSocket_Peer::waitForTotalSuccessCount(quint64 numSuccess, int stepTimeout) { QReadLocker locker(&m_recLock); if(!m_recFailureMessages.isEmpty()) return false; if(m_recSuccessCount >= numSuccess) return true; QElapsedTimer timer; timer.start(); while(m_recSuccessCount < numSuccess) { QCoreApplication::processEvents(); // Return if we did not receive data or if we received an failure timer.restart(); quint64 old = m_recSuccessCount; if(!m_recValuesChanged.wait(&m_recLock, stepTimeout) || !m_recFailureMessages.isEmpty()) { if(old == m_recSuccessCount) { if(timer.elapsed() >= stepTimeout) break; else QCoreApplication::processEvents(); } } } return (!m_recFailureMessages.isEmpty() && m_recSuccessCount >= numSuccess); }
void TestQgsSvgCache::changeImage() { bool inCache; QgsSvgCache cache; // no minimum time between checks cache.mFileModifiedCheckTimeout = 0; //copy an image to the temp folder QString tempImagePath = QDir::tempPath() + "/svg_cache.svg"; QString originalImage = TEST_DATA_DIR + QStringLiteral( "/test_symbol_svg.svg" ); if ( QFileInfo::exists( tempImagePath ) ) QFile::remove( tempImagePath ); QFile::copy( originalImage, tempImagePath ); //render it through the cache QImage img = cache.svgAsImage( tempImagePath, 200, QColor( 0, 0, 0 ), QColor( 0, 0, 0 ), 1.0, 1.0, inCache ); QVERIFY( imageCheck( "svgcache_changed_before", img, 30 ) ); // wait a second so that modified time is different QElapsedTimer t; t.start(); while ( !t.hasExpired( 1000 ) ) {} //replace the image in the temp folder QString newImage = TEST_DATA_DIR + QStringLiteral( "/test_symbol_svg2.svg" ); QFile::remove( tempImagePath ); QFile::copy( newImage, tempImagePath ); //re-render it img = cache.svgAsImage( tempImagePath, 200, QColor( 0, 0, 0 ), QColor( 0, 0, 0 ), 1.0, 1.0, inCache ); QVERIFY( imageCheck( "svgcache_changed_after", img, 30 ) ); // repeat, with minimum time between checks QgsSvgCache cache2; QFile::remove( tempImagePath ); QFile::copy( originalImage, tempImagePath ); img = cache2.svgAsImage( tempImagePath, 200, QColor( 0, 0, 0 ), QColor( 0, 0, 0 ), 1.0, 1.0, inCache ); QVERIFY( imageCheck( "svgcache_changed_before", img, 30 ) ); // wait a second so that modified time is different t.restart(); while ( !t.hasExpired( 1000 ) ) {} //replace the image in the temp folder QFile::remove( tempImagePath ); QFile::copy( newImage, tempImagePath ); //re-render it - not enough time has elapsed between checks, so file modification time will NOT be rechecked and // existing cached image should be used img = cache2.svgAsImage( tempImagePath, 200, QColor( 0, 0, 0 ), QColor( 0, 0, 0 ), 1.0, 1.0, inCache ); QVERIFY( imageCheck( "svgcache_changed_before", img, 30 ) ); }
void qAnimationDlg::preview() { //we'll take the rendering time into account! QElapsedTimer timer; timer.start(); setEnabled(false); //reset the interpolators and count the total number of frames int frameCount = countFrameAndResetInterpolators(); //show progress dialog QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this); progressDialog.setWindowTitle("Preview"); progressDialog.show(); QApplication::processEvents(); double fps = fpsSpinBox->value(); int frameIndex = 0; for ( size_t i=0; i<m_videoSteps.size(); ++i ) { VideoStepItem& currentVideoStep = m_videoSteps[i]; //theoretical waiting time per frame qint64 delay_ms = static_cast<int>(1000 * currentVideoStep.duration_sec / fps); cc2DViewportObject currentParams; while ( currentVideoStep.interpolator.nextView( currentParams ) ) { timer.restart(); applyViewport ( ¤tParams ); qint64 dt_ms = timer.elapsed(); progressDialog.setValue(++frameIndex); QApplication::processEvents(); if (progressDialog.wasCanceled()) { break; } //remaining time if (dt_ms < delay_ms) { int wait_ms = static_cast<int>(delay_ms - dt_ms); #if defined(CC_WINDOWS) ::Sleep( wait_ms ); #else usleep( wait_ms * 1000 ); #endif } } } //reset view onCurrentStepChanged( getCurrentStepIndex() ); setEnabled(true); }
void timerEvent(QTimerEvent *ev) override { if (ev->timerId() == timer.timerId() && painter) { qreal const t = el.restart() / (qreal)10; for (auto &s : state) s.advance(t, dst.rect()); update(); } }
void MainWindow::on_action_open_triggered() { QString xlsFile = QFileDialog::getOpenFileName(this,QString(),QString(),"excel(*.xls *.xlsx)"); if(xlsFile.isEmpty()) return; QElapsedTimer timer; timer.start(); if(m_xls.isNull()) m_xls.reset(new ExcelBase); m_xls->open(xlsFile); qDebug()<<"open cost:"<<timer.elapsed()<<"ms";timer.restart(); m_xls->setCurrentSheet(1); m_xls->readAll(m_datas); qDebug()<<"read data cost:"<<timer.elapsed()<<"ms";timer.restart(); QVariantListListModel* md = qobject_cast<QVariantListListModel*>(ui->tableView->model()); if(md) { md->updateData(); } qDebug()<<"show data cost:"<<timer.elapsed()<<"ms";timer.restart(); }
void IndexBuilder::writeSnapshots(Reader &reader, KZip &zip) { static const qint64 SNAPSHOT_INTERVAL_MS = 1000; // snapshot interval in milliseconds static const int SNAPSHOT_MIN_ACTIONS = 200; // minimum number of actions between snapshots paintcore::LayerStack image; net::LayerListModel layermodel; canvas::StateTracker statetracker(&image, &layermodel, 1); MessageRecord msg; int snapshotCounter = 0; QElapsedTimer timer; timer.start(); while(true) { if(_abortflag.load()) return; msg = reader.readNext(); if(msg.status == MessageRecord::END_OF_RECORDING) break; else if(msg.status == MessageRecord::INVALID) continue; protocol::MessagePtr m(msg.message); if(m->isCommand()) { statetracker.receiveCommand(m); ++snapshotCounter; } // Save a snapshot every SNAPSHOT_INTERVAL or at every marker. (But no more often than SNAPSHOT_MIN_ACTIONS) // Note. We use the actual elapsed rendering time to decide when to snapshot. This means that (ideally), // the time it takes to jump to a snapshot is at most SNAPSHOT_INTERVAL milliseconds (+ the time it takes to load the snapshot) if(m_index.snapshots().isEmpty() || ((timer.hasExpired(SNAPSHOT_INTERVAL_MS) || m->type() == protocol::MSG_MARKER) && snapshotCounter>=SNAPSHOT_MIN_ACTIONS)) { qint64 streampos = reader.filePosition(); emit progress(streampos); canvas::StateSavepoint sp = statetracker.createSavepoint(-1); QBuffer buf; buf.open(QBuffer::ReadWrite); { QDataStream ds(&buf); sp.toDatastream(ds); } int snapshotIdx = m_index.m_snapshots.size(); zip.writeFile(QString("snapshot-%1").arg(snapshotIdx), buf.data()); m_index.m_snapshots.append(SnapshotEntry(streampos, reader.currentIndex())); snapshotCounter = 0; timer.restart(); } } }
bool CWsgiEngine::finalizeHeadersWrite(Context *c, quint16 status, const Headers &headers, void *engineData) { auto conn = static_cast<QIODevice*>(engineData); conn->write("HTTP/1.1 ", 9); int msgLen; const char *msg = httpStatusMessage(status, &msgLen); conn->write(msg, msgLen); auto sock = qobject_cast<TcpSocket*>(conn); const auto headersData = headers.data(); if (sock->headerClose == 1) { sock->headerClose = 0; } bool hasDate = false; auto it = headersData.constBegin(); const auto endIt = headersData.constEnd(); while (it != endIt) { const QString key = it.key(); const QString value = it.value(); if (sock->headerClose == 0 && key == QLatin1String("connection")) { if (value.compare(QLatin1String("close"), Qt::CaseInsensitive) == 0) { sock->headerClose = 2; } else { sock->headerClose = 1; } } else if (!hasDate && key == QLatin1String("date")) { hasDate = true; } QString ret(QLatin1String("\r\n") + camelCaseHeader(key) + QLatin1String(": ") + value); conn->write(ret.toLatin1()); ++it; } if (!hasDate) { static QByteArray lastDate = dateHeader(); static QElapsedTimer timer = timerSetup(); if (timer.hasExpired(1000)) { lastDate = dateHeader(); timer.restart(); } conn->write(lastDate); } static QByteArray server = serverHeader(); conn->write(server); return conn->write("\r\n\r\n", 4) == 4; }
void idupdaterui::downloadProgress( qint64 recvd, qint64 total ) { static QElapsedTimer timer; static qint64 lastRecvd = 0; if( timer.hasExpired( 1000 ) ) { m_downloadStatus->setText( QString( "%1 KB/s" ).arg( (recvd - lastRecvd) / timer.elapsed() ) ); lastRecvd = recvd; timer.restart(); } m_downloadProgress->setMaximum( total ); m_downloadProgress->setValue( recvd ); }
void MapView::tileDownloaded(QNetworkReply *reply) { //recreate original request from reply and delete it from the current requests QElapsedTimer timer; timer.start(); TileRequest finishedRequest(reply); currentRequests.removeAll(finishedRequest); //check to see if any requests are left in stack if (!requestStack.isEmpty()) { //pop the last request in the stack TileRequest request = requestStack.takeLast(); //proceed to download the request networkManager->get(request); currentRequests.append(request); } QByteArray *data = new QByteArray(reply->readAll()); QByteArray *cpData = new QByteArray(*data); qDebug("curreq"+QString::number(currentRequests.size())+ " reqstck"+QString::number(requestStack.size())); //check if actual data was returned if (data->length()!=0) //todo: check if data is valid { //AddTileToDBThread* t = new AddTileToDBThread(finishedRequest.z(),finishedRequest.x(),finishedRequest.y(),cpData,finishedRequest.mapSource().url); //t->start(); //the method below also checks presence of tile in db addTileToDB(finishedRequest.z(),finishedRequest.x(),finishedRequest.y(),data,finishedRequest.mapSource().url); //qDebug(qPrintable("Tile image file size:" + QString::number(data.length()) + " bits" // "(x:"+QString::number(x)+" y:"+QString::number(y)+" z:"+QString::number(z)+")")); } else emit noNetwork(); qDebug("adding tile to db took "+QString::number(timer.elapsed())); timer.restart(); //check if zoomlevel and map source did not change while downloading if( currentZoom == finishedRequest.z() && finishedRequest.mapSource().url == MapSource.url) placeTile(data, finishedRequest.x(), finishedRequest.y(), finishedRequest.z()); qDebug("placing tile took "+QString::number(timer.elapsed())); reply->deleteLater(); //do not 'delete reply;' }
void unorderedMapBench() { QElapsedTimer timer; timer.start(); std::unordered_map<int,triple> data; triple point; int i; for (i = 0; i < RAND_COUNT; ++i) { point.x = i; point.y = rand(); point.z = rand(); //printf("%d %d %d %d\n", i, point.x, point.y, point.z); data[i] = point; } qDebug() << Q_FUNC_INFO << "creation: elapsed" << timer.elapsed(); timer.restart(); foreach (auto t, data) { if (t.second.x % 1000 == 0) doSomething(t.second.x); } qDebug() << " foreach: elapsed" << timer.elapsed(); timer.restart(); for( auto it = data.begin(); it != data.end(); ++it ) { if (it->second.x % 1000 == 0) doSomething(it->second.x); } qDebug() << " range-based for: elapsed" << timer.elapsed(); timer.restart(); for (i = 0; i < RAND_COUNT; ++i) { auto it = data.find(i); Q_ASSERT(it->second.x == i); if (it->second.x % 1000 == 0) doSomething(it->first); } qDebug() << " find: elapsed" << timer.elapsed(); }
int restartExample() { //![3] QElapsedTimer timer; int count = 1; timer.start(); do { count *= 2; slowOperation2(count); } while (timer.restart() < 250); return count; //![3] }
void Evnav::checkCachePerformance() { QVector<int> hist(50); int bin = 10; QElapsedTimer timer; timer.start(); computeDistanceHistogram(hist, bin); auto e1 = timer.nsecsElapsed(); timer.restart(); computeDistanceHistogram(hist, bin); auto e2 = timer.nsecsElapsed(); qDebug() << "e1:" << e1 << "ms" << " e2:" << e2 << "ms"; qDebug() << "hist:" << hist; }
void MainGui::OnFrameSwapped() { static bool isStarted = false; static QElapsedTimer timer; static long long lastTime; if (!isStarted) { isStarted = true; timer.start(); } else if (timer.elapsed() > 500) { long long currentTime = timer.elapsed(); double fps = 1000.0 / (currentTime - lastTime); setWindowTitle(QString("FPS: %1").arg(QString::number(fps, 'f', 2))); timer.restart(); } lastTime = timer.elapsed(); }
void autobots_toutiao::onStart() { control_status = true; //QString interval = ui.lineEdit_interval->text(); int nseconds = 10;//interval.toInt(); int count = 0; while(control_status) { QNetworkCookieJar* cookie = new QNetworkCookieJar(this); network.GetManager().setCookieJar(cookie); QString temp = QStringLiteral("第"); count ++; QString temp2; temp2.setNum(count); ui.lineEdit_msg->setText(temp + temp2); GetContent(); // 1.获取验证码 QString pid; QString str = GetValidateCode(pid); // QElapsedTimer t; // t.start(); // while(t.elapsed()<1000) // QCoreApplication::processEvents(); // 2.发送请求 SubmitVote(str, pid); QElapsedTimer t; t.restart(); while(t.elapsed()<nseconds*1000) QCoreApplication::processEvents(); } }
bool MainWindow::copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist) { if(isPathExcept(fromDir)) return true; // 流逝时间计算 static QElapsedTimer et; et.start(); QDir sourceDir(fromDir); QDir targetDir(toDir); if(!targetDir.exists()){ /** 如果目标目录不存在,则进行创建 */ if(!targetDir.mkdir(targetDir.path())) { qDebug() << "mkdir " + targetDir.filePath(sourceDir.dirName()) + " failed"; } } QFileInfoList fileInfoList = sourceDir.entryInfoList(); foreach(QFileInfo fileInfo, fileInfoList) { if(fileInfo.fileName() == "." || fileInfo.fileName() == "..") continue; if(fileInfo.isDir()) { /**< 当为目录时,递归的进行 copy */ qDebug() << fileInfo.filePath() << "-> " << targetDir.filePath(fileInfo.fileName()); copyDirectoryFiles(fileInfo.filePath(),targetDir.filePath(fileInfo.fileName()),coverFileIfExist); } else { // 同步文件 synTwoFiles(fileInfo.filePath(),targetDir.filePath(fileInfo.fileName())); } if(et.elapsed() > 300) { QApplication::processEvents(); et.restart(); qDebug() << "回到UI"; } } return true; }
void LS3DatastoreXML::dbClose(bool saveOnClose) { LS3ElapsedAutoTimer timer("LS3DatastoreXML::dbClose"); QElapsedTimer time; time.restart(); if (data!=NULL) { data->setDoEmitSignals(false); mapper->submit(); } //qDebug()<<"dbClose(saveOnClose="<<saveOnClose<<"): "<<time.elapsed()<<"ms: mapper->submit()"; time.restart(); emit disconnectWidgets(); //qDebug()<<"dbClose(saveOnClose="<<saveOnClose<<"): "<<time.elapsed()<<"ms: emit disconnectWidgets()"; time.restart(); emit databaseLoaded(false); //qDebug()<<"dbClose(saveOnClose="<<saveOnClose<<"): "<<time.elapsed()<<"ms: emit databaseLoaded(false)"; time.restart(); emit databaseClosed(true); //qDebug()<<"dbClose(saveOnClose="<<saveOnClose<<"): "<<time.elapsed()<<"ms: emit databaseClosed(true)"; time.restart(); if (!m_currentFile.isEmpty() && saveOnClose) dbSave(m_currentFile); //qDebug()<<"dbClose(saveOnClose="<<saveOnClose<<"): "<<time.elapsed()<<"ms: dbSave(m_currentFile)"; time.restart(); resetFieldDefinitions(); //qDebug()<<"dbClose(saveOnClose="<<saveOnClose<<"): "<<time.elapsed()<<"ms: resetFieldDefinitions()"; time.restart(); clearSelection(); //qDebug()<<"dbClose(saveOnClose="<<saveOnClose<<"): "<<time.elapsed()<<"ms: clearSelection()"; time.restart(); getReferencTreeModel()->clear(); //qDebug()<<"dbClose(saveOnClose="<<saveOnClose<<"): "<<time.elapsed()<<"ms: getReferencTreeModel()->clear()"; time.restart(); keywordsdata->setStringList(QStringList()); //qDebug()<<"dbClose(saveOnClose="<<saveOnClose<<"): "<<time.elapsed()<<"ms: keywordsdata->setStringList()"; time.restart(); authorsdata->setStringList(QStringList()); //qDebug()<<"dbClose(saveOnClose="<<saveOnClose<<"): "<<time.elapsed()<<"ms: authorsdata->setStringList(QStringList())"; time.restart(); topicsdata->setStringList(QStringList()); //qDebug()<<"dbClose(saveOnClose="<<saveOnClose<<"): "<<time.elapsed()<<"ms: topicsdata->setStringList(QStringList())"; time.restart(); if (data!=NULL) { data->setDoEmitSignals(true); } data->newFile(); //qDebug()<<"dbClose(saveOnClose="<<saveOnClose<<"): "<<time.elapsed()<<"ms: data->newFile()"; time.restart(); m_currentFile=""; m_databaseLoaded=true; emit filenameChanged(m_currentFile); //qDebug()<<"dbClose(saveOnClose="<<saveOnClose<<"): "<<time.elapsed()<<"ms: emit filenameChanged(m_currentFile)"; time.restart(); }
std::pair<double, double> runSimulation(openstudio::runmanager::ErrorEstimation &t_ee, double t_rotation) { openstudio::model::Model m = openstudio::model::exampleModel(); openstudio::model::Building b = *m.building(); b.setNorthAxis(b.northAxis() + t_rotation); QElapsedTimer et; et.start(); openstudio::SqlFile sqlfile1(runSimulation(m, false)); qint64 originaltime = et.restart(); openstudio::SqlFile sqlfile2(runSimulation(m, true)); qint64 reducedtime = et.elapsed(); openstudio::path weatherpath = resourcesPath() / openstudio::toPath("runmanager") / openstudio::toPath("USA_CO_Golden-NREL.724666_TMY3.epw"); openstudio::isomodel::ForwardTranslator translator; openstudio::isomodel::UserModel userModel = translator.translateModel(m); userModel.setWeatherFilePath(weatherpath); openstudio::isomodel::SimModel simModel = userModel.toSimModel(); openstudio::isomodel::ISOResults isoResults = simModel.simulate(); LOG_FREE(Info, "runSimulation", "OriginalTime " << originaltime << " reduced " << reducedtime); std::vector<double> variables; variables.push_back(t_rotation); openstudio::runmanager::FuelUses fuses0(0); try { fuses0 = t_ee.approximate(variables); } catch (const std::exception &e) { LOG_FREE(Info, "runSimulation", "Unable to generate estimate: " << e.what()); } openstudio::runmanager::FuelUses fuses3 = t_ee.add(userModel, isoResults, "ISO", variables); openstudio::runmanager::FuelUses fuses2 = t_ee.add(sqlfile2, "Estimation", variables); openstudio::runmanager::FuelUses fuses1 = t_ee.add(sqlfile1, "FullRun", variables); LOG_FREE(Info, "runSimulation", "Comparing Full Run to linear approximation"); compareUses(fuses1, fuses0); LOG_FREE(Info, "runSimulation", "Comparing Full Run to error adjusted ISO run"); return std::make_pair(compare(*sqlfile1.netSiteEnergy(), isoResults.totalEnergyUse()), compareUses(fuses1, fuses3)); }
/// @brief a method to draw all the particles contained in the system void Emitter::draw(const ngl::Mat4 &_VP, const ngl::Mat4 &_rot) { QElapsedTimer timer; timer.start(); ngl::NGLMessage::addMessage("Starting emitter draw\n"); ngl::ShaderLib *shader=ngl::ShaderLib::instance(); shader->use("Point"); shader->setUniform("MVP",_VP*_rot); m_vao->bind(); m_vao->draw(); m_vao->unbind(); ngl::NGLMessage::addMessage(fmt::format("Finished draw took %d milliseconds\n",timer.elapsed())); if(m_export==true) { timer.restart(); exportFrame(); ngl::NGLMessage::addMessage(fmt::format("Alembic Export took %d milliseconds\n",timer.elapsed())); } }
CameraFrame CameraOpenCV::getFrame(){ CameraFrame frame; if (!capturing) { cerr << "ERROR: Not capturing on camera. Call startCapture() before lockFrame()." << endl; return frame; } cv::Mat cvframe, out; QElapsedTimer timer; timer.start(); for (int i = 0; i < 30; ++i) { m_videoCap.grab(); qint64 t = timer.restart(); if (t >= 0.3 * m_grabTimeMS) break; //cout << "Time to grab frame to short (" << t << "), retaking image ..." << endl; } bool ret = m_videoCap.retrieve(cvframe); if (!ret || cvframe.empty()) { cerr << "ERROR: Did not get a image from the camera." << endl; return frame; } cv::cvtColor(cvframe, out, cv::COLOR_BGR2GRAY); // Copy frame address and properties frame.memory = out.data; frame.width = out.cols; frame.height = out.rows; frame.sizeBytes = frame.height * out.step; return frame; }
bool MSqlQuery::exec() { if (!m_db) { // Database structure's been deleted return false; } if (m_last_prepared_query.isEmpty()) { LOG(VB_GENERAL, LOG_ERR, "MSqlQuery::exec(void) called without a prepared query."); return false; } #if DEBUG_RECONNECT if (random() < RAND_MAX / 50) { LOG(VB_GENERAL, LOG_INFO, "MSqlQuery disconnecting DB to test reconnection logic"); m_db->m_db.close(); } #endif // Database connection down. Try to restart it, give up if it's still // down if (!m_db->isOpen() && !Reconnect()) { LOG(VB_GENERAL, LOG_INFO, "MySQL server disconnected"); return false; } QElapsedTimer timer; timer.start(); bool result = QSqlQuery::exec(); qint64 elapsed = timer.elapsed(); // if the query failed with "MySQL server has gone away" // Close and reopen the database connection and retry the query if it // connects again if (!result && QSqlQuery::lastError().number() == 2006 && Reconnect()) result = QSqlQuery::exec(); if (!result) { QString err = MythDB::GetError("MSqlQuery", *this); MSqlBindings tmp = QSqlQuery::boundValues(); bool has_null_strings = false; for (MSqlBindings::iterator it = tmp.begin(); it != tmp.end(); ++it) { if (it->type() != QVariant::String) continue; if (it->isNull() || it->toString().isNull()) { has_null_strings = true; *it = QVariant(QString("")); } } if (has_null_strings) { bindValues(tmp); timer.restart(); result = QSqlQuery::exec(); elapsed = timer.elapsed(); } if (result) { LOG(VB_GENERAL, LOG_ERR, QString("Original query failed, but resend with empty " "strings in place of NULL strings worked. ") + "\n" + err); } } if (VERBOSE_LEVEL_CHECK(VB_DATABASE, LOG_INFO)) { QString str = lastQuery(); // Database logging will cause an infinite loop here if not filtered // out if (!str.startsWith("INSERT INTO logging ")) { // Sadly, neither executedQuery() nor lastQuery() display // the values in bound queries against a MySQL5 database. // So, replace the named placeholders with their values. QMapIterator<QString, QVariant> b = boundValues(); while (b.hasNext()) { b.next(); str.replace(b.key(), '\'' + b.value().toString() + '\''); } LOG(VB_DATABASE, LOG_INFO, QString("MSqlQuery::exec(%1) %2%3%4") .arg(m_db->MSqlDatabase::GetConnectionName()).arg(str) .arg(QString(" <<<< Took %1ms").arg(QString::number(elapsed))) .arg(isSelect() ? QString(", Returned %1 row(s)") .arg(size()) : QString())); } } return result; }
void grabFramesLoop(bool &streaming, framebufferinfo &info, QQueue<QByteArray> &queue, QOrientationReading::Orientation &orientation) { QImage img(info.scrinfo.xres, info.scrinfo.yres, QImage::Format_RGBA8888); QBuffer imgBuffer; QElapsedTimer timer; timer.start(); int frames = 0; int old = 0; int now = 0; int line = info.fix_scrinfo.line_length / 4; QByteArray ba; QTransform transform; while(streaming) { for (unsigned int y = 0; y < info.scrinfo.yres; ++y) { QRgb *rowData = (QRgb*)img.scanLine(y); for (unsigned int x = 0; x < info.scrinfo.xres; ++x) { rowData[x] = *((unsigned int *)info.fbmmap + ((x + info.scrinfo.xoffset) + (y + info.scrinfo.yoffset) * line)); } } imgBuffer.setBuffer(&ba); imgBuffer.open(QIODevice::WriteOnly); if(orientation != QOrientationReading::TopUp) { switch (orientation) { case QOrientationReading::TopDown: img = img.transformed(transform.rotate(180)); break; case QOrientationReading::LeftUp: img = img.transformed(transform.rotate(90)); break; case QOrientationReading::RightUp: img = img.transformed(transform.rotate(-90)); break; default: break; } img.save(&imgBuffer, "JPG", info.compression); transform.reset(); // reset to original (correct width x height) img = QImage(info.scrinfo.xres, info.scrinfo.yres, QImage::Format_RGBA8888); } else { img.save(&imgBuffer, "JPG", info.compression); } queue.enqueue(ba); imgBuffer.close(); ++frames; now = timer.elapsed(); if(now > old) { info.frametime = now - old; } old = now; // get average fps over the last 50 frames if(frames == 50) { info.fps = round(50.0 / (timer.restart() / 1000.0)); frames = 0; } } return; }
void FFT::excute(ImageData<float> &imgData) { omp_set_num_threads(m_num_threads); if (m_plan.size() < m_num_threads) { plan(); } if (imgData.dataSize() != m_size.x * m_size.y * m_size.z) { std::cerr << "Error: FFT wrong image size" << std::endl; exit(1); } #pragma omp parallel shared(imgData) { int id = omp_get_thread_num(); QElapsedTimer timer; timer.start(); #pragma omp for schedule(dynamic) for (int i = 0; i < imgData.channels(); i++) { auto data = imgData.getChannelImage(i); auto in = m_in[id]; auto plan = m_plan[id]; memcpy(in, data->data(), imgData.dataSize() * sizeof(fftwf_complex)); fftwf_execute(plan); memcpy(data->data(), in, imgData.dataSize() * sizeof(fftwf_complex)); #pragma omp critical std::cout << "Thread " << id << " CPU FFT channel " << m_index << ':' << i << " | " << timer.restart() << " ms" << std::endl; } } omp_set_num_threads(1); }