Legacy:GetSeconds

From Spherical
Revision as of 06:38, 30 June 2015 by Bruce Pascoe (talk | contribs) (Created page with "Obtains the amount of time in seconds, in floating point, elapsed since an arbitrary time. This function typically has sub-microsecond precision, making it useful for benchmar...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Obtains the amount of time in seconds, in floating point, elapsed since an arbitrary time. This function typically has sub-microsecond precision, making it useful for benchmarking or any other situation where you need higher-precision timing than GetTime() can give you. A Sphere 2.0 engine such as minisphere is required to use this function.

Usage

number GetSeconds();


Examples

var time = GetSeconds();

The above gets the number of seconds passed since some predetermined time, and places it in the time variable.

var start_time = GetSeconds();
// Code that needs to be timed
// ...
var duration = GetTime() - start_time;

The above example will find out how long a particular piece of code runs for.

var done = false;
var fps = GetFrameRate();
var updates_performed = 0;
var start_time = GetSeconds();
while (!done)
{
  while (updates_performed < (GetSeconds() - start_time) * fps)
  {
    // Update game here
    // ...
    updates_performed++;
  }
  // Draw the game screen here
  // ...
  FlipScreen();
}

The above example is one way to regulate the speed of a Sphere game inside a JavaScript loop. The game code will have to be separated into updates (player input processing, moving entities, checking collisions, etc.) and drawing (drawing sprites, the map, score, etc.).

var FPS = 60;                // The desired FPS
var delayTime = 1.0/FPS;     // The time between frames
var lastTime = GetSeconds(); // The time of the last frame
while(loopCondition)         // While we should continue looping
{
  if(GetSeconds() > lastTime + delayTime) // If enough time has elapsed
  {
    lastTime = GetSeconds(); // Record the time of this frame
    doStuff();               // Do your stuff
  }
  drawStuff();               // Draw your stuff
}

This example is an alternative to the one above. Obviously, doStuff() and drawStuff() will correspond with functions that actually process the game logic and draw the game state respectively.

Notes

  • The starting time can be assumed to be constant throughout the running of a game. Thus GetSeconds() is very useful as a tool to pace JavaScript loops, which would normally run at different speeds on different systems.
  • Core JavaScript provides a similar mechanism via the Date object's Date.getTime() method. This counter, if used with a Date object that reflects the current time, displays the number of milliseconds since midnight 01 January, 1970 UTC. Refer to the links for more information.
  • Unlike GetTime(), the value returned by this function is not subject to wraparound.

See also

API:Script/navbox