Time.time running slow

Isn't Time.time supposed to measure time in real seconds? I noticed that while looping a one-second sound during 10 seconds (as measured with Time.time) the sound plays 17 times instead of 10. I did this both in the editor and as a standalone (on windows). What gives? Is there any way to improve the timing of unity?

When doing this I have a pretty high framerate (~3ms per frame in the editor). Can't you trust the time functions at high framerates?

3 Answers

3

Using a sound loop isn't really a good way to measure time, but in any case, Time.time is affected by the timescale. With the timescale set to 1.0, use this script and a stopwatch and see if they match:

function Update () {
    Debug.Log (Time.time);
}

(The answer is yes they will match, although note that the stats display is not the framerate you're actually getting. Use this for actual frames per second.)

Did you make sure that the timescale is 1.0?

I think you want Time.timeSinceLevelLoad http://unity3d.com/support/documentation/ScriptReference/Time-timeSinceLevelLoad.html if that doesn't work then adjust the timeScale http://unity3d.com/support/documentation/ScriptReference/Time-timeScale.html till it syncronises properly. Also try building and running it as an .exe (or mac equivalent) instead of inside unity editor.

I did this simple time class using system.datetime:

public class MyTime : MonoBehaviour
{

    protected static System.DateTime startTime;

    public static float deltaTime;

    protected static float m_totalAccumulatedTime;

    void Start ()

    {

        startTime = System.DateTime.Now;

        m_totalAccumulatedTime = 0f;    

    }

    void LateUpdate()

    {

        System.TimeSpan elapsed = System.DateTime.Now - startTime;

        deltaTime = (float)(elapsed.TotalMilliseconds*0.001f) - m_totalAccumulatedTime;

        m_totalAccumulatedTime += deltaTime;

    }
}

And it turns out to work quite well. Now when I compare with a stopwatch the printed time from accumulating MyTime.deltaTime is quite accurate.