本文整理汇总了C++中QElapsedTimer::elapsed方法的典型用法代码示例。如果您正苦于以下问题:C++ QElapsedTimer::elapsed方法的具体用法?C++ QElapsedTimer::elapsed怎么用?C++ QElapsedTimer::elapsed使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QElapsedTimer
的用法示例。
在下文中一共展示了QElapsedTimer::elapsed方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: render
void QSGDefaultRenderer::render()
{
#if defined (QML_RUNTIME_TESTING)
static bool dumpTree = qApp->arguments().contains(QLatin1String("--dump-tree"));
if (dumpTree) {
printf("\n\n");
QSGNodeDumper::dump(rootNode());
}
#endif
#ifdef RENDERER_DEBUG
debugTimer.invalidate();
debugTimer.start();
geometryNodesDrawn = 0;
materialChanges = 0;
#endif
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_BLEND);
glFrontFace(isMirrored() ? GL_CW : GL_CCW);
glDisable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthMask(true);
glDepthFunc(GL_GREATER);
#if defined(QT_OPENGL_ES)
glClearDepthf(0);
#else
glClearDepth(0);
#endif
glDisable(GL_SCISSOR_TEST);
glClearColor(m_clear_color.redF(), m_clear_color.greenF(), m_clear_color.blueF(), m_clear_color.alphaF());
#ifdef RENDERER_DEBUG
int debugtimeSetup = debugTimer.elapsed();
#endif
bindable()->clear(clearMode());
#ifdef RENDERER_DEBUG
int debugtimeClear = debugTimer.elapsed();
#endif
QRect r = viewportRect();
glViewport(r.x(), deviceRect().bottom() - r.bottom(), r.width(), r.height());
m_current_projection_matrix = projectionMatrix();
m_current_model_view_matrix.setToIdentity();
m_currentClip = 0;
glDisable(GL_STENCIL_TEST);
m_currentMaterial = 0;
m_currentProgram = 0;
m_currentMatrix = 0;
if (m_rebuild_lists) {
m_opaqueNodes.reset();
m_transparentNodes.reset();
m_currentRenderOrder = 1;
buildLists(rootNode());
m_rebuild_lists = false;
}
#ifdef RENDERER_DEBUG
int debugtimeLists = debugTimer.elapsed();
#endif
if (m_needs_sorting) {
if (!m_opaqueNodes.isEmpty()) {
qSort(&m_opaqueNodes.first(), &m_opaqueNodes.first() + m_opaqueNodes.size(),
m_sort_front_to_back
? nodeLessThanWithRenderOrder
: nodeLessThan);
}
m_needs_sorting = false;
}
#ifdef RENDERER_DEBUG
int debugtimeSorting = debugTimer.elapsed();
#endif
m_renderOrderMatrix.setToIdentity();
m_renderOrderMatrix.scale(1, 1, qreal(1) / m_currentRenderOrder);
glDisable(GL_BLEND);
glDepthMask(true);
#ifdef QML_RUNTIME_TESTING
if (m_render_opaque_nodes)
#endif
{
#if defined (QML_RUNTIME_TESTING)
if (dumpTree)
qDebug() << "Opaque Nodes:";
#endif
renderNodes(m_opaqueNodes);
}
//.........这里部分代码省略.........
示例2: run
//.........这里部分代码省略.........
needInitGame = false;
}
UpdateInputState(input_state);
for (int i = 0; i < controllistCount; i++) {
if (input_state->pad_buttons_down & controllist[i].emu_id) {
__CtrlButtonDown(controllist[i].psp_id);
}
if (input_state->pad_buttons_up & controllist[i].emu_id) {
__CtrlButtonUp(controllist[i].psp_id);
}
}
__CtrlSetAnalog(input_state->pad_lstick_x, input_state->pad_lstick_y);
EndInputState(input_state);
glstate.Restore();
glViewport(0, 0, pixel_xres, pixel_yres);
Matrix4x4 ortho;
ortho.setOrtho(0.0f, dp_xres, dp_yres, 0.0f, -1.0f, 1.0f);
glsl_bind(UIShader_Get());
glUniformMatrix4fv(UIShader_Get()->u_worldviewproj, 1, GL_FALSE, ortho.getReadPtr());
ReapplyGfxState();
Core_Run();
// Hopefully coreState is now CORE_NEXTFRAME
if (coreState == CORE_NEXTFRAME) {
// set back to running for the next frame
coreState = CORE_RUNNING;
qint64 time = timer.elapsed();
const int frameTime = (1.0f/60.0f) * 1000;
gameMutex.unlock();
if(time < frameTime)
{
glWindow->doneCurrent();
msleep(frameTime-time);
glWindow->makeCurrent();
}
gameMutex.lock();
timer.start();
}
fbo_unbind();
UIShader_Prepare();
uiTexture->Bind(0);
glViewport(0, 0, pixel_xres, pixel_yres);
ui_draw2d.Begin(DBMODE_NORMAL);
//if (g_Config.bShowTouchControls)
// DrawGamepad(ui_draw2d);
glsl_bind(UIShader_Get());
ui_draw2d.End();
ui_draw2d.Flush(UIShader_Get());
// Tiled renderers like PowerVR should benefit greatly from this. However - seems I can't call it?
#if defined(USING_GLES2)
示例3: preview
void qAnimationDlg::preview()
{
//we'll take the rendering time into account!
QElapsedTimer timer;
timer.start();
setEnabled(false);
size_t vp1 = previewFromSelectedCheckBox->isChecked() ? static_cast<size_t>(getCurrentStepIndex()) : 0;
//count the total number of frames
int frameCount = countFrames(loopCheckBox->isChecked() ? 0 : vp1);
int fps = fpsSpinBox->value();
//show progress dialog
QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this);
progressDialog.setWindowTitle("Preview");
progressDialog.show();
progressDialog.setModal(true);
progressDialog.setAutoClose(false);
QApplication::processEvents();
assert(stepSelectionList->count() >= m_videoSteps.size());
int frameIndex = 0;
size_t vp2 = 0;
while (getNextSegment(vp1, vp2))
{
Step& step1 = m_videoSteps[vp1];
Step& step2 = m_videoSteps[vp2];
//theoretical waiting time per frame
qint64 delay_ms = static_cast<int>(1000 * step1.duration_sec / fps);
int frameCount = static_cast<int>( fps * step1.duration_sec );
ViewInterpolate interpolator(step1.viewport, step2.viewport);
interpolator.setMaxStep(frameCount);
cc2DViewportObject currentParams;
while ( 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
}
}
if (progressDialog.wasCanceled())
{
break;
}
if (vp2 == 0)
{
assert(loopCheckBox->isChecked());
frameIndex = 0;
}
vp1 = vp2;
}
//reset view
onCurrentStepChanged(getCurrentStepIndex());
setEnabled(true);
}
示例4: lock
bool QtLockedFile::lock(LockMode mode, bool block)
{
#ifdef ZOMBOID
QElapsedTimer elapsed;
elapsed.start();
#endif
if (!isOpen()) {
qWarning("QtLockedFile::lock(): file is not opened");
return false;
}
if (mode == m_lock_mode)
return true;
if (m_lock_mode != 0)
unlock();
if (m_semaphore_hnd == 0) {
QFileInfo fi(*this);
QString sem_name = QString::fromLatin1(SEMAPHORE_PREFIX)
+ fi.absoluteFilePath().toLower();
m_semaphore_hnd = CreateSemaphoreW(0, SEMAPHORE_MAX, SEMAPHORE_MAX,
(TCHAR*)sem_name.utf16());
if (m_semaphore_hnd == 0) {
qWarning("QtLockedFile::lock(): CreateSemaphore: %s",
errorCodeToString(GetLastError()).toLatin1().constData());
return false;
}
}
bool gotMutex = false;
int decrement;
if (mode == ReadLock) {
decrement = 1;
} else {
decrement = SEMAPHORE_MAX;
if (m_mutex_hnd == 0) {
QFileInfo fi(*this);
QString mut_name = QString::fromLatin1(MUTEX_PREFIX)
+ fi.absoluteFilePath().toLower();
m_mutex_hnd = CreateMutexW(NULL, FALSE, (TCHAR*)mut_name.utf16());
if (m_mutex_hnd == 0) {
qWarning("QtLockedFile::lock(): CreateMutex: %s",
errorCodeToString(GetLastError()).toLatin1().constData());
return false;
}
}
DWORD res = WaitForSingleObject(m_mutex_hnd, block ? INFINITE : 0);
if (res == WAIT_TIMEOUT)
return false;
if (res == WAIT_FAILED) {
qWarning("QtLockedFile::lock(): WaitForSingleObject (mutex): %s",
errorCodeToString(GetLastError()).toLatin1().constData());
return false;
}
gotMutex = true;
}
for (int i = 0; i < decrement; ++i) {
DWORD res = WaitForSingleObject(m_semaphore_hnd, block ? INFINITE : 0);
if (res == WAIT_TIMEOUT) {
if (i) {
// A failed nonblocking rw locking. Undo changes to semaphore.
if (ReleaseSemaphore(m_semaphore_hnd, i, NULL) == 0) {
qWarning("QtLockedFile::unlock(): ReleaseSemaphore: %s",
errorCodeToString(GetLastError()).toLatin1().constData());
// Fall through
}
}
if (gotMutex)
ReleaseMutex(m_mutex_hnd);
return false;
}
if (res != WAIT_OBJECT_0) {
if (gotMutex)
ReleaseMutex(m_mutex_hnd);
qWarning("QtLockedFile::lock(): WaitForSingleObject (semaphore): %s",
errorCodeToString(GetLastError()).toLatin1().constData());
return false;
}
}
m_lock_mode = mode;
if (gotMutex)
ReleaseMutex(m_mutex_hnd);
#ifdef ZOMBOID
if (elapsed.elapsed() > 0)
qDebug() << "QtLockedFile::lock took" << elapsed.elapsed() << "ms";
#endif
return true;
}
示例5: if
//.........这里部分代码省略.........
arcToSegments(point1,point2,tempPath.toolpath);
arcToSegments(point2,point1,tempPath.toolpath);
}
else if(e.pad.shape=='R')
{
struct myRect r=rectToMyRect(e.pad,toolDiameter);
s.point=r.p1;
s.type='L';
tempPath.segmentList.append(s);
s.point=r.p2;
s.type='L';
tempPath.segmentList.append(s);
s.point=r.p3;
s.type='L';
tempPath.segmentList.append(s);
s.point=r.p4;
s.type='L';
tempPath.segmentList.append(s);
IntPoint point;
point.X=r.p1.x();point.Y=r.p1.y();
tempPath.toolpath<<point;
point.X=r.p2.x();point.Y=r.p2.y();
tempPath.toolpath<<point;
point.X=r.p3.x();point.Y=r.p3.y();
tempPath.toolpath<<point;
point.X=r.p4.x();point.Y=r.p4.y();
tempPath.toolpath<<point;
}
else if(e.pad.shape=='O')
{
struct track t=obroundToTrack(e.pad);
struct myRect r=trackToMyRect(t,toolDiameter);
s.point=r.p1;
s.type='L';
tempPath.segmentList.append(s);
s.point=r.p2;
s.type='C';
tempPath.segmentList.append(s);
s.point=r.p3;
s.type='L';
tempPath.segmentList.append(s);
s.point=r.p4;
s.type='C';
tempPath.segmentList.append(s);
IntPoint point;
point.X=r.p1.x();point.Y=r.p1.y();
tempPath.toolpath<<point;
arcToSegments(r.p2,r.p3,tempPath.toolpath);
point.X=r.p4.x();point.Y=r.p4.y();
tempPath.toolpath<<point;
arcToSegments(r.p4,r.p1,tempPath.toolpath);
}
}
tempCPaths.push_back(tempPath.toolpath);
tempPath.boundingRect=expandBoundingRect(e.boundingRect,toolDiameter);
tempToolPathNetPath.pathList.append(tempPath);
}
SimplifyPolygons(tempCPaths,tempToolPathNetPath.toolpath,pftNonZero);
netPathList.append(tempToolPathNetPath);
}
cToolpathIntersects(netPathList,tpCollisionNum);
int sum=0;
for(int i=0;i<tpCollisionNum.size();i++)
{
collisionToolpath temp=tpCollisionNum.at(i);
sum+=temp.pair.size();
for(int j=0;j<temp.pair.size();j++)
{
net n=p.netList.at(temp.pair.at(j).p1);
n.collisionFlag=true;
p.netList.replace(temp.pair.at(j).p1,n);
n=p.netList.at(temp.pair.at(j).p2);
n.collisionFlag=true;
p.netList.replace(temp.pair.at(j).p2,n);
}
}
qDebug()<<"toolpath collision num="<<sum;
collisionSum=sum;
Paths tempPath;
for(i=0;i<netPathList.size();i++)
tempPath.push_back(netPathList.at(i).toolpath.at(0));
SimplifyPolygons(tempPath,totalToolpath,pftNonZero);
for(i=0;i<netPathList.size();i++)
if(netPathList.at(i).toolpath.size()>1)
{
for(j=1;j<netPathList.at(i).toolpath.size();j++)
totalToolpath.push_back(netPathList.at(i).toolpath.at(j));
}
time=timer.elapsed();
}
示例6: doAction
//.........这里部分代码省略.........
}
//display the progress dialog
QProgressDialog pDlg;
pDlg.setWindowTitle("CSF");
pDlg.setLabelText("Computing....");
pDlg.setCancelButton(0);
pDlg.show();
QApplication::processEvents();
QElapsedTimer timer;
timer.start();
//instantiation a CSF class
CSF csf(csfPC);
// setup parameter
csf.params.k_nearest_points = 1;
csf.params.bSloopSmooth = csf_postprocessing;
csf.params.time_step = 0.65;
csf.params.class_threshold = class_threshold;
csf.params.cloth_resolution = cloth_resolution;
csf.params.rigidness = csf_rigidness;
csf.params.iterations = MaxIteration;
//to do filtering
std::vector<int> groundIndexes, offGroundIndexes;
ccMesh* clothMesh = 0;
if (!csf.do_filtering(groundIndexes, offGroundIndexes, ExportClothMesh, clothMesh, m_app))
{
m_app->dispToConsole("Process failed", ccMainAppInterface::ERR_CONSOLE_MESSAGE);
return;
}
m_app->dispToConsole(QString("[CSF] %1% of points classified as ground points").arg((groundIndexes.size() * 100.0) / count, 0, 'f', 2), ccMainAppInterface::STD_CONSOLE_MESSAGE);
m_app->dispToConsole(QString("[CSF] Timing: %1 s.").arg(timer.elapsed() / 1000.0, 0, 'f', 1), ccMainAppInterface::STD_CONSOLE_MESSAGE);
//extract ground subset
ccPointCloud* groundpoint = 0;
{
CCLib::ReferenceCloud groundpc(pc);
if (groundpc.reserve(static_cast<unsigned>(groundIndexes.size())))
{
for (unsigned j = 0; j < groundIndexes.size(); ++j)
{
groundpc.addPointIndex(groundIndexes[j]);
}
groundpoint = pc->partialClone(&groundpc);
}
}
if (!groundpoint)
{
m_app->dispToConsole("Failed to extract the ground subset (not enough memory)", ccMainAppInterface::WRN_CONSOLE_MESSAGE);
}
//extract off-ground subset
ccPointCloud* offgroundpoint = 0;
{
CCLib::ReferenceCloud offgroundpc(pc);
if (offgroundpc.reserve(static_cast<unsigned>(offGroundIndexes.size())))
{
for (unsigned k = 0; k < offGroundIndexes.size(); ++k)
{
offgroundpc.addPointIndex(offGroundIndexes[k]);
}
offgroundpoint = pc->partialClone(&offgroundpc);
}
}
示例7: run
void CorrespondenceSearch::run()
{
QElapsedTimer allTimer; allTimer.start();
auto & paths = generator->computedAssignments;
QVector<ParticleMesh*> input; input << sA << sB;
QVector<Particles> inputParticles; inputParticles << sA->particles << sB->particles;
auto boxA = sA->bbox();
std::vector<double> pathScores( paths.size(), DBL_MAX );
bool abort = false;
// Evaluate correspondences
#pragma omp parallel for
for(int pi = 0; pi < (int)paths.size(); pi++)
{
#pragma omp flush (abort)
if(!abort)
{
if(pd->wasCanceled()){
abort = true;
#pragma omp flush (abort)
}
double score = 0;
auto & path = paths[pi];
// Compute dense correspondence
QVector<Particles> particles = inputParticles;
for(auto & pairing : path) PartCorresponder::correspondSegments( pairing, input, particles );
// Evaluate correspondence:
{
int numSamples = 4;
int start = 1; // Skipping initial configuration
for(int sample = start; sample < numSamples; sample++)
{
double t = double(sample) / (numSamples-1);
for(auto & p : particles[0])
{
// one-to-none
if( p.correspondence > particles[1].size() )
{
score += (p.pos /*- boxA.center()*/).norm() * 100;
continue;
}
auto blended = AlphaBlend(t, p.pos, particles[1][p.correspondence].pos);
score += (blended - p.pos).norm();
}
}
}
pathScores[pi] = score;
emit( pathComputed() );
}
}
/// Assign best correspondence:
{
auto bestPath = std::min_element(pathScores.begin(), pathScores.end()) - pathScores.begin();
bestCorrespondence = paths[bestPath];
}
// Timing
property["allSearchTime"].setValue( (int)allTimer.elapsed() );
emit( done() );
}
示例8: now
unsigned long now()
{
return timer.elapsed();
}
示例9: readData
void PeerObject::readData()
{
// static int readCount = 0;
// m_dbgLog.write("PeerObject::readData()");
// m_dbgLog.write(QString("(%1)\n").arg(++readCount).toLatin1());
// m_dbgLog.flush();
static quint64 totalRead = 0;
while(m_socket->availableData()) {
// Read size
quint32 orgSize = 0;
quint32 size = 0;
if(m_socket->bytesAvailable() < sizeof(size)) {
callSlotQueued(this, "checkReadData");
return;
}
if(m_socket->read((char *)&orgSize, sizeof(orgSize)) < sizeof(orgSize))
qFatal("Could not read size!");
size = qFromBigEndian<quint32>(orgSize);
// if(m_socket->read((char*)&size, sizeof(size)) < sizeof(size))
// qFatal("Could not checksum!");
// size = qFromBigEndian<quint32>(size);
// qDebug("Peer: size to read: %u", size);
if(size == 0) {
qDebug("Peer: PeerObject::readData() - zero size data");
m_peerSocket->write(QStringLiteral("fReceived zero size").toLatin1());
// m_peerSocket->flush();
if(m_close)
close(1);
return;
}
// Read data with specified size
QElapsedTimer timer;
QByteArray data(size, (char)'\0');
// qDebug("PeerObject::readData() - size: %u", size);
// m_dbgLog.write("Reading: ");
// m_dbgLog.write(QStringLiteral("%1 bytes").arg(size).toLatin1());
// m_dbgLog.write("\n");
// m_dbgLog.flush();
// Read max 30 seconds
timer.start();
qint64 tmp = 0;
qint64 read = 0;
bool waiting = false;
while(read < size && timer.elapsed() < 10000) {
if(m_socket->bytesAvailable() < 1) {
waiting = true;
// Logger::log("Read bytes (TestLocalSocket_Ext_PO)", totalRead + read, "bW", "Begin waiting for bytes");
if(m_socket->waitForReadyRead(10000 - timer.elapsed()))
timer.restart();
}
tmp = m_socket->read(data.data() + read, size - read);
if(tmp < 0) {
m_peerSocket->write(QStringLiteral("fCould not read data!").toLatin1());
// m_peerSocket->flush();
close(1);
return;
}
// Logger::log("Read tmp bytes (TestLocalSocket_Ext_PO)", tmp);
read += tmp;
}
// if(waiting)
// Logger::log("Read bytes (TestLocalSocket_Ext_PO)", totalRead + read, "eW", "End waiting for bytes");
// m_dbgLog.write("Ok\n");
// m_dbgLog.flush();
// Check read data size
if(read < size) {
qDebug("Peer: PeerObject::readData() - not enough data");
m_peerSocket->write(QStringLiteral("fDid not receive enough data. Expected: %1; Got: %2").arg(size).arg(data.size()).toLatin1());
// m_peerSocket->flush();
// m_dbgLog.write("Did not receive enough data");
// m_dbgLog.write("\n");
// m_dbgLog.flush();
if(m_close)
close(1);
//.........这里部分代码省略.........
示例10: main
int main(int argc, char *argv[])
{
QCoreApplication application(argc, argv);
QContactManager manager(QLatin1String("org.nemomobile.contacts.sqlite"));
QContactFetchRequest request;
request.setManager(&manager);
qint64 elapsedTimeTotal = 0;
QElapsedTimer asyncTotalTimer;
asyncTotalTimer.start();
// Fetch all, no optimization hints
for (int i = 0; i < 3; ++i) {
QElapsedTimer timer;
timer.start();
request.start();
request.waitForFinished();
qint64 elapsed = timer.elapsed();
qDebug() << i << ": Fetch completed in" << elapsed << "ms";
elapsedTimeTotal += elapsed;
}
// Skip relationships
QContactFetchHint hint;
hint.setOptimizationHints(QContactFetchHint::NoRelationships);
request.setFetchHint(hint);
for (int i = 0; i < 3; ++i) {
QElapsedTimer timer;
timer.start();
request.start();
request.waitForFinished();
qint64 elapsed = timer.elapsed();
qDebug() << i << ": No-relationships fetch completed in" << elapsed << "ms";
elapsedTimeTotal += elapsed;
}
// Reduce data access
#ifdef USING_QTPIM
hint.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactName::Type << QContactAddress::Type);
#else
hint.setDetailDefinitionsHint(QStringList() << QContactName::DefinitionName << QContactAddress::DefinitionName);
#endif
request.setFetchHint(hint);
for (int i = 0; i < 3; ++i) {
QElapsedTimer timer;
timer.start();
request.start();
request.waitForFinished();
qint64 elapsed = timer.elapsed();
qDebug() << i << ": Reduced data fetch completed in" << elapsed << "ms";
elapsedTimeTotal += elapsed;
}
// Reduce number of results
hint.setMaxCountHint(request.contacts().count() / 8);
request.setFetchHint(hint);
for (int i = 0; i < 3; ++i) {
QElapsedTimer timer;
timer.start();
request.start();
request.waitForFinished();
qint64 elapsed = timer.elapsed();
qDebug() << i << ": Max count fetch completed in" << elapsed << "ms";
elapsedTimeTotal += elapsed;
}
qint64 asyncTotalElapsed = asyncTotalTimer.elapsed();
// Time some synchronous operations. First, generate the test data.
qsrand((int)asyncTotalElapsed);
QList<int> nbrContacts;
nbrContacts << 10 << 100 << 500 << 1000 << 2000;
QList<QList<QContact> > testData;
qDebug() << "\n\n\n\n\n";
qDebug() << "Generating test data for timings...";
for (int i = 0; i < nbrContacts.size(); ++i) {
int howMany = nbrContacts.at(i);
QList<QContact> newTestData;
newTestData.reserve(howMany);
for (int j = 0; j < howMany; ++j) {
newTestData.append(generateContact());
}
testData.append(newTestData);
}
// Perform the timings - these all create new contacts and assume an "empty" initial database
//.........这里部分代码省略.........
示例11: main
//.........这里部分代码省略.........
// vecSel << 76, 74, 13, 61, 97, 94, 75, 71, 60, 56, 26, 57, 56, 0, 52, 72, 33, 86, 96, 67;
std::cout << "Select following epochs to average:\n" << vecSel << std::endl;
FiffEvoked evoked = data.average(raw.info, tmin*raw.info.sfreq, floor(tmax*raw.info.sfreq + 0.5), vecSel);
QStringList ch_sel_names = t_Fwd.info.ch_names;
FiffEvoked pickedEvoked = evoked.pick_channels(ch_sel_names);
//########################################################################################
// RAP MUSIC Source Estimate
//
// Cluster forward solution;
//
MNEForwardSolution t_clusteredFwd = t_Fwd.cluster_forward_solution(t_annotationSet, 20);//40);
//
// Compute inverse solution
//
PwlRapMusic t_pwlRapMusic(t_clusteredFwd, false, numDipolePairs);
#ifdef BENCHMARK
MNESourceEstimate sourceEstimate;
QList<qint64> qVecElapsedTime;
for(qint32 i = 0; i < 100; ++i)
{
//Benchmark time
QElapsedTimer timer;
timer.start();
sourceEstimate = t_pwlRapMusic.calculateInverse(pickedEvoked);
qVecElapsedTime.append(timer.elapsed());
}
double meanTime = 0.0;
qint32 offset = 19;
qint32 c = 0;
for(qint32 i = offset; i < qVecElapsedTime.size(); ++i)
{
meanTime += qVecElapsedTime[i];
++c;
}
meanTime /= (double)c;
double varTime = 0;
for(qint32 i = offset; i < qVecElapsedTime.size(); ++i)
varTime += pow(qVecElapsedTime[i] - meanTime,2);
varTime /= (double)c - 1.0f;
varTime = sqrt(varTime);
qDebug() << "RAP-MUSIC calculation took" << meanTime << "+-" << varTime << "ms in average";
#else
int iWinSize = 200;
if(doMovie) {
t_pwlRapMusic.setStcAttr(iWinSize, 0.6f);
}
MNESourceEstimate sourceEstimate = t_pwlRapMusic.calculateInverse(pickedEvoked);
if(doMovie) {
//Select only the activations once
示例12: ts
/// @brief ctor
/// @param _pos the position of the emitter
/// @param _numParticles the number of particles to create
Emitter::Emitter(ngl::Vec3 _pos, unsigned int _numParticles, ngl::Vec3 *_wind )
{
m_wind=_wind;
Particle p;
GLParticle g;
ngl::Random *rand=ngl::Random::instance();
ngl::NGLMessage::addMessage("Starting emitter ctor\n");
QElapsedTimer timer;
timer.start();
m_pos=_pos;
m_particles.reset( new Particle[_numParticles]);
m_glparticles.reset( new GLParticle[_numParticles]);
m_vao= ngl::VAOFactory::createVAO(ngl::simpleVAO,GL_POINTS);
float pointOnCircleX= cosf(ngl::radians(m_time))*4.0f;
float pointOnCircleZ= sinf(ngl::radians(m_time))*4.0f;
ngl::Vec3 end(pointOnCircleX,2.0,pointOnCircleZ);
end=end-m_pos;
#pragma omp parallel for ordered schedule(dynamic)
for (unsigned int i=0; i< _numParticles; ++i)
{
g.px=p.m_px=m_pos.m_x;
g.py=p.m_py=m_pos.m_y;
g.pz=p.m_pz=m_pos.m_z;
ngl::Vec3 c=rand->getRandomColour3();
p.m_r=g.pr=c.m_r;
p.m_g=g.pg=c.m_g;
p.m_b=g.pb=c.m_b;
p.m_dx=end.m_x+rand->randomNumber(2)+0.5f;
p.m_dy=end.m_y+rand->randomPositiveNumber(10)+0.5f;
p.m_dz=end.m_z+rand->randomNumber(2)+0.5f;
p.m_gravity=-9.0f;
p.m_currentLife=0.0f;
m_particles[i]=p;
m_glparticles[i]=g;
}
m_numParticles=_numParticles;
// create the VAO and stuff data
m_vao->bind();
// now copy the data
m_vao->setData(ngl::SimpleVAO::VertexData(m_numParticles*sizeof(GLParticle),m_glparticles[0].px));
m_vao->setVertexAttributePointer(0,3,GL_FLOAT,sizeof(GLParticle),0);
m_vao->setVertexAttributePointer(1,3,GL_FLOAT,sizeof(GLParticle),3);
m_vao->setNumIndices(m_numParticles);
m_vao->unbind();
ngl::NGLMessage::addMessage(fmt::format("Finished filling array took %d milliseconds\n",timer.elapsed()));
/// @note this demo is based on alembic/lib/Alembic/AbcGeom/Tests/PointsTest.cpp
// create an alembic Geometry output archive called particlesOut.abc
Alembic::AbcCoreAbstract::MetaData md;
// CreateArchiveWithInfo(
// Alembic::AbcCoreOgawa::WriteArchive(), "archiveInfo.abc",
// appWriter, userStr, md );
// m_archive.reset(new AbcG::OArchive(Alembic::AbcCoreOgawa::WriteArchive(),"particlesOut.abc",md) );
namespace Abc = Alembic::Abc;
using namespace Abc;
OArchive archive;
std::string appWriter = "ngl Alembic Export";
std::string userStr = "Simple Demo of exporting points with alembic";
// m_archive.reset( CreateArchiveWithInfo(
// Alembic::AbcCoreOgawa::WriteArchive(), "archiveInfo.abc",
// appWriter, userStr, md )) ;
//
m_archive=CreateArchiveWithInfo(
Alembic::AbcCoreOgawa::WriteArchive(), "particlesOut.abc",
appWriter, userStr, md );
// create time sampling of 24 fps at frame 0 to start
AbcG::TimeSampling ts(1.0f/24.0f, 0.0f);
// get the archive top
//AbcG::OObject topObj( *m_archive.get(), AbcG::kTop );
AbcG::OObject topObj( m_archive, AbcG::kTop );
// then add in our time sampling.
Alembic::Util::uint32_t tsidx = topObj.getArchive().addTimeSampling(ts);
// this is our particle outputs to write to each frame
m_partsOut.reset( new AbcG::OPoints(topObj, "simpleParticles", tsidx) );
// now add a colour property to the alembic file for out points
AbcG::MetaData mdata;
AbcG::SetGeometryScope( mdata, AbcG::kVaryingScope );
AbcG::OPointsSchema &pSchema = m_partsOut->getSchema();
std::cout<<"Schema "<<pSchema.getNumSamples()<<" "<<pSchema.valid()<<"\n";
m_rgbOut.reset(new AbcG::OC3fArrayProperty( pSchema, "Cd", tsidx ));
}
示例13: update
/// @brief a method to update each of the particles contained in the system
void Emitter::update()
{
QElapsedTimer timer;
timer.start();
ngl::NGLMessage::addMessage("Starting emitter update\n");
m_vao->bind();
ngl::Real *glPtr=m_vao->mapBuffer();
unsigned int glIndex=0;
static int rot=0;
static float time=0.0f;
float pointOnCircleX= cosf(ngl::radians(time))*4.0f;
float pointOnCircleZ= sinf(ngl::radians(time))*4.0f;
ngl::Vec3 end(pointOnCircleX,2.0f,pointOnCircleZ);
end=end-m_pos;
//end.normalize();
time+=m_time;
#pragma omp parallel for
for(unsigned int i=0; i<m_numParticles; ++i)
{
m_particles[i].m_currentLife+=0.002f;
// use projectile motion equation to calculate the new position
// x(t)=Ix+Vxt
// y(t)=Iy+Vxt-1/2gt^2
// z(t)=Iz+Vzt
m_particles[i].m_px=m_pos.m_x+(m_wind->m_x*m_particles[i].m_dx*m_particles[i].m_currentLife);
m_particles[i].m_py= m_pos.m_y+(m_wind->m_y*m_particles[i].m_dy*m_particles[i].m_currentLife)+m_particles[i].m_gravity*(m_particles[i].m_currentLife*m_particles[i].m_currentLife);
m_particles[i].m_pz=m_pos.m_z+(m_wind->m_z*m_particles[i].m_dz*m_particles[i].m_currentLife);
glPtr[glIndex]=m_particles[i].m_px;
glPtr[glIndex+1]=m_particles[i].m_py;
glPtr[glIndex+2]=m_particles[i].m_pz;
// if we go below the origin re-set
if(m_particles[i].m_py <= m_pos.m_y-0.01f)
{
++rot;
m_particles[i].m_px=m_pos.m_x;
m_particles[i].m_pz=m_pos.m_y;
m_particles[i].m_px=m_pos.m_z;
m_particles[i].m_currentLife=0.0;
ngl::Random *rand=ngl::Random::instance();
m_particles[i].m_dx=end.m_x+rand->randomNumber(2)+0.5f;
m_particles[i].m_dy=end.m_y+rand->randomPositiveNumber(10)+0.5f;
m_particles[i].m_dz=end.m_z+rand->randomNumber(2)+0.5f;
glPtr[glIndex]=m_particles[i].m_px;
glPtr[glIndex+1]=m_particles[i].m_py;
glPtr[glIndex+2]=m_particles[i].m_pz;
ngl::Vec3 c=rand->getRandomColour3();
glPtr[glIndex+3]=c.m_r;
glPtr[glIndex+4]=c.m_g;
glPtr[glIndex+5]=c.m_b;
m_particles[i].m_r=c.m_r;
m_particles[i].m_g=c.m_g;
m_particles[i].m_b=c.m_b;
}
#pragma omp atomic
glIndex+=6;
}
m_vao->unmapBuffer();
m_vao->unbind();
ngl::NGLMessage::addMessage(fmt::format("Finished update array took %d milliseconds\n",timer.elapsed()));
}
示例14: extractFacets
//.........这里部分代码省略.........
break;
default:
assert(false);
break;
}
//create scalar field to host the fusion result
const char c_defaultSFName[] = "facet indexes";
int sfIdx = pc->getScalarFieldIndexByName(c_defaultSFName);
if (sfIdx < 0)
sfIdx = pc->addScalarField(c_defaultSFName);
if (sfIdx < 0)
{
m_app->dispToConsole("Couldn't allocate a new scalar field for computing fusion labels! Try to free some memory ...",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
return;
}
pc->setCurrentScalarField(sfIdx);
//computation
QElapsedTimer eTimer;
eTimer.start();
ccProgressDialog pDlg(true,m_app->getMainWindow());
bool success = true;
if (algo == CellsFusionDlg::ALGO_KD_TREE)
{
//we need a kd-tree
QElapsedTimer eTimer;
eTimer.start();
ccKdTree kdtree(pc);
if (kdtree.build(s_errorMaxPerFacet/2,errorMeasure,s_minPointsPerFacet,1000,&pDlg))
{
qint64 elapsedTime_ms = eTimer.elapsed();
m_app->dispToConsole(QString("[qFacets] Kd-tree construction timing: %1 s").arg(static_cast<double>(elapsedTime_ms)/1.0e3,0,'f',3),ccMainAppInterface::STD_CONSOLE_MESSAGE);
success = ccKdTreeForFacetExtraction::FuseCells(
&kdtree,
s_errorMaxPerFacet,
errorMeasure,
s_kdTreeFusionMaxAngle_deg,
static_cast<PointCoordinateType>(s_kdTreeFusionMaxRelativeDistance),
true,
&pDlg);
}
else
{
m_app->dispToConsole("Failed to build Kd-tree! (not enough memory?)",ccMainAppInterface::ERR_CONSOLE_MESSAGE);
success = false;
}
}
else if (algo == CellsFusionDlg::ALGO_FAST_MARCHING)
{
int result = FastMarchingForFacetExtraction::ExtractPlanarFacets(
pc,
static_cast<unsigned char>(s_octreeLevel),
static_cast<ScalarType>(s_errorMaxPerFacet),
errorMeasure,
s_fmUseRetroProjectionError,
&pDlg,
pc->getOctree());
success = (result >= 0);
}
if (success)
示例15: exec
MongoShellExecResult ScriptEngine::exec(const std::string &originalScript, const std::string &dbName)
{
QMutexLocker lock(&_mutex);
if (!_scope) {
_failedScope = true;
return MongoShellExecResult(true, "Connection error. Uninitialized mongo scope.");
}
/*
* Replace all commands ('show dbs', 'use db' etc.) with call
* to shellHelper('show', 'dbs') and so on.
*/
std::string stdstr(originalScript);
pcrecpp::RE re("^(show|use|set) (\\w+)$",
pcrecpp::RE_Options(PCRE_CASELESS|PCRE_MULTILINE|PCRE_NEWLINE_ANYCRLF));
re.GlobalReplace("shellHelper('\\1', '\\2');", &stdstr);
/*
* Statementize (i.e. extract all JavaScript statements from script) and
* execute each statement one by one
*/
std::vector<std::string> statements;
std::string error;
bool result = statementize(stdstr, statements, error);
if (!result && statements.size() == 0) {
statements.push_back("print(__robomongoResult.error)");
}
std::vector<MongoShellResult> results;
use(dbName);
for (std::vector<std::string>::const_iterator it = statements.begin(); it != statements.end(); ++it)
{
std::string statement = *it;
// clear global objects
__objects.clear();
__type = "";
__finished = false;
__logs.str("");
if (true /* ! wascmd */) {
try {
bool failed = false;
QElapsedTimer timer;
timer.start();
if ( _scope->exec( statement , "(shell)" , false , true , false, _timeoutSec * 1000) ) {
_scope->exec( "__robomongoLastRes = __lastres__; shellPrintHelper( __lastres__ );",
"(shell2)" , true , true , false, _timeoutSec * 1000);
}
else { // failed to run script
failed = true;
}
qint64 elapsed = timer.elapsed();
std::string logs = __logs.str();
std::string answer = logs.c_str();
std::string type = __type.c_str();
if (failed)
return MongoShellExecResult(true, answer);
std::vector<MongoDocumentPtr> docs = MongoDocument::fromBsonObj(__objects);
if (!answer.empty() || docs.size() > 0)
results.push_back(prepareResult(type, answer, docs, elapsed));
}
catch (const std::exception &e) {
std::cout << "error:" << e.what() << std::endl;
}
}
}
return prepareExecResult(results);
}