开发者

Clean way to get ms elapsed since last loop?

Is there a cleaner way to express the following?

// initialize several vars here

long lastT = 0; 
while (looping) {
    long now = currentTimeMillis(); 
    long elapsed = now - lastT; 
    lastT = now;

    // code here
}
开发者_Python百科

Presumably I only need long elapsed=... (and probably the loop itself), but the other lines can either be condensed, or moved elsewhere. But what's the best way to do that?

The language used is not important, though the above was written in Java.


You could say

long lastT = 0;
while (looping) {
  long elapsed = currentTimeMillis() - lastT;
  lastT += elapsed;

  // actual code goes here
}

which saves you one line and one variable declaration at a cost of one extra arithmetic operation. Note that in contexts where times are floating-point values (as, e.g., Python's time.time returns a double) doing this will eventually incur lots of aggregated rounding errors.

If you're doing a lot of this and it bothers you, you could make an elapsed-time-counting class that encapsulates this stuff. Then your loop could be:

Stopwatch sw = new Stopwatch();
while (looping) {
  long elapsed = sw.timeSinceLastReading();
  // actual code goes here
}

For what it's worth, I generally use pretty much the same structure as the code you gave.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜