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
1067 // on shutdown and stop... so we want to loop and sleep until we've spent our time in1067 // on shutdown and stop... so we want to loop and sleep until we've spent our time in
1068 // purgatory, constantly checking to see if our script was asked to end1068 // purgatory, constantly checking to see if our script was asked to end
1069 bool processedEvents = false;1069 bool processedEvents = false;
1070 while (!_isFinished && clock::now() < sleepUntil) {1070 if (!_isFinished) {
1071 1071 PROFILE_RANGE(script, "processEvents-sleep");
1072 {1072 std::chrono::milliseconds sleepFor =
1073 PROFILE_RANGE(script, "processEvents-sleep");1073 std::chrono::duration_cast<std::chrono::milliseconds>(sleepUntil - clock::now());
1074 QCoreApplication::processEvents(); // before we sleep again, give events a chance to process1074 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();
1075 }1083 }
1076 processedEvents = true;1084 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);
1088 }1085 }
1089 1086
1090 PROFILE_RANGE(script, "ScriptMainLoop");1087 PROFILE_RANGE(script, "ScriptMainLoop");