emscripten-core / emscripten-core/emscripten

Maximum speed of emscripten_set_main_loop() with setTimeout mode.

Open
#18,021 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
27.6k
Forks
3.6k
Avg merge
1d 1h
Merged PRs (30d)
105

Description

There is a ralated issue https://github.com/emscripten-core/emscripten/issues/4200 which fixed the fps when there is some time spent inside the main loop function. But it seems not enough.

I've tested on Chrome for a emscripten_set_main_loop with FPS=1000 and my main loop function cost for 4ms, and currently it runs on a 125fps(8ms per frame) . The performance trace is like
![image](https://user-images.githubusercontent.com/1000408/194694399-fdde926c-47b3-48d2-bfee-27d3a01e214a.png)

Currently the time until next tick is calculated as following:
```
var timeUntilNextTick = Math.max(0, Browser.mainLoop.tickStartTime + value - _emscripten_get_now()) | 0;
setTimeout(Browser.mainLoop.runner, timeUntilNextTick);
```
When the main loop funtion cost 4ms, the timeUntilNextTick will be 0. But it seems that Chrome will force it to be 4ms.

**My suggestion of solution:**
So can we put the Browser.mainLoop.scheduler() before the Browser.mainLoop.runIter(browserIterationFunc) instead of the tickStartTime calculations? Thus we just scheduler the next tick before the task runs to avoid the time spent in main loop function.
I tried it and the trace is like this. The fps become 250(4ms per frame) and it looks to be the max speed.
![image](https://user-images.githubusercontent.com/1000408/194694732-ebf46106-50ec-4b59-92ba-3f4202a1b25f.png)

Related code: https://github.com/emscripten-core/emscripten/blob/main/src/library_browser.js

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.