History

use QEventLoop and a timer for a less CPU using sleep + event-processing

Seth Alves committed 9 years ago

Commit bf7da711 parent 9ae39081 file · +13 −16Browse files

Showing the changes to libraries/script-engine/src/ScriptEngine.cpp (1 of 1 file). Show all

Unified · Split

libraries/script-engine/src/ScriptEngine.cpp+13−16
@@ -1067,24 +1067,21 @@ void ScriptEngine::run() { · 1066 unmodified lines
10671067 // on shutdown and stop... so we want to loop and sleep until we've spent our time in
10681068 // purgatory, constantly checking to see if our script was asked to end
10691069 bool processedEvents = false;
1070− while (!_isFinished && clock::now() < sleepUntil) {
1071−
1072− {
1073− PROFILE_RANGE(script, "processEvents-sleep");
1074− QCoreApplication::processEvents(); // before we sleep again, give events a chance to process
1070+ if (!_isFinished) {
1071+ PROFILE_RANGE(script, "processEvents-sleep");
1072+ std::chrono::milliseconds sleepFor =
1073+ std::chrono::duration_cast<std::chrono::milliseconds>(sleepUntil - clock::now());
1074+ if (sleepFor > std::chrono::milliseconds(0)) {
1075+ QEventLoop loop;
1076+ QTimer timer;
1077+ timer.setSingleShot(true);
1078+ connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
1079+ timer.start(sleepFor);
1080+ loop.exec();
1081+ } else {
1082+ QCoreApplication::processEvents();
10751083 }
10761084 processedEvents = true;
1077−
1078− // If after processing events, we're past due, exit asap
1079− if (clock::now() >= sleepUntil) {
1080− break;
1081− }
1082−
1083− // We only want to sleep a small amount so that any pending events (like timers or invokeMethod events)
1084− // will be able to process quickly.
1085− static const int SMALL_SLEEP_AMOUNT = 100;
1086− auto smallSleepUntil = clock::now() + static_cast<std::chrono::microseconds>(SMALL_SLEEP_AMOUNT);
1087− std::this_thread::sleep_until(smallSleepUntil);
10881085 }
10891086
10901087 PROFILE_RANGE(script, "ScriptMainLoop");