2016-11-10 106 views
0

我遇到了requestAnimationFrame()的性能問題。requestAnimationFrame()性能問題

請考慮以下代碼。這是一個簡單的循環,打印自上一幀以來的時間,每次這個時間增量大於20ms。

const glob_time_info = {delta_time: 0.0, last_frame: performance.now()}; 

var render = function (timestamp) { 
    glob_time_info.delta_time = timestamp - glob_time_info.last_frame; 
    glob_time_info.last_frame = timestamp; 
    if(glob_time_info.delta_time > 20) 
     console.log(glob_time_info.delta_time); 
    requestAnimationFrame(render); 
}; 
render(performance.now()); 

正如我理解requestAnimationFrame此片段不應該打印任何東西,因爲它試圖每秒運行60次(60Hz作爲我的顯示器)。因此時間增量應該總是在16-17ms左右。

但它每隔幾秒打印33ms的時間。 爲什麼?

我使用Chrome 54和Firefox 49。經歷過這個在Windows 10我擁有i5-6600


UPDATE 這裏尼特的腳本爲Windows和Ubuntu的輸出。 Windows,你在做什麼? 的Windows 10(PC): enter image description here Windows 8的(相同的上網本如下): enter image description here 的Ubuntu(同上上網本): enter image description here

+0

它被固定在16並且當我運行時改變。可能與您的計算機正在做的垃圾收集和其他東西有關。 – JonSG

+1

「試」是關鍵字,如果有什麼阻塞線程,即使幾毫秒,它不再成功 – adeneo

+0

我也想過GC,但每隔幾秒?並且他必須收集什麼:)如果每隔幾秒鐘幀速下降到30FPS或更低時,如何製作流暢的動畫 –

回答

0

由於特拉維斯法官在它的相關操作系統的意見陳述。

這個性能問題沒有出現在linux上。所以我們沒有什麼可以做的。

+0

「它與操作系統有關」---好吧,這是一個Windows 10和一個不太強大的CPU:我每次迭代得到15-16ms。 – zerkms

+0

我也得到15-16ms,但每隔幾秒鐘就會出現峯值。你有沒有試過我的代碼片段? –

+0

不,我運行其他答案。 – zerkms

2

很容易測試您的假設,即問題與您正在運行的平臺有關 - 衡量性能。

稍後,運行​​多次類似於您的操作,並記下每次運行的時間戳。之後,簡單地可視化結果。

var times = []; 
 
var measure = function() { 
 
    times.push(new Date().getTime()); 
 
    if (times.length > 100) return draw(); 
 
    requestAnimationFrame(measure); 
 
}; 
 
var draw = function() { 
 
    var dataset = { 
 
    x: [], 
 
    y: [], 
 
    type: 'bar' 
 
    }; 
 
    var layout = { 
 
    xaxis: { 
 
     title: 'measurement #' 
 
    }, 
 
    yaxis: { 
 
     title: 'iteration duration (ms)' 
 
    }, 
 
    height: 250 
 
    }; 
 
    var options = { 
 
    displayModeBar: false 
 
    }; 
 
    times.reduce(function(previous, current, i) { 
 
    dataset.x.push(i); 
 
    dataset.y.push(current - previous); 
 
    return current; 
 
    }, times.shift()); 
 
    Plotly.newPlot('target', [dataset], layout, options); 
 
} 
 
measure();
#target { 
 
    margin-top: -50px; 
 
}
<script src="https://cdn.plot.ly/plotly-1.2.0.min.js"></script> 
 
<div id="target"></div>

您可以運行在不同的操作系統和不同的瀏覽器相同的模擬,看看是否可以進一步縮小問題的範圍。

+0

謝謝!我把這些圖片放在問題中。 –