Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time.time vs DateTime.UtcNow.Millisecond performance in Unity3D?

I need to keep track of the time a lot in my multiplayer game built with Unity, in order to know when the packet of data came in. What would have better performance in Unity, Time.time or DateTime.UtcNow.Millisecond? And by how much would the performance difference vary?

like image 376
daniel metlitski Avatar asked Mar 13 '17 01:03

daniel metlitski


1 Answers

It's the best to test that by yourself. You're the one that knows your application best and can tell what is the most optimal solution in particluar conditions. This is some simple test script you can use. It just save current timestamp with unity/c# method and logs time needed for that operation.

public class TimeTest : MonoBehaviour
{
    public bool UseUnityFuntion;

    private string msg;

    void Update ()
    {
        var stopwatch = Stopwatch.StartNew();
        msg = UseUnityFuntion 
            ? Time.time.ToString() 
            : DateTime.UtcNow.Millisecond.ToString();
        stopwatch.Stop();
        UnityEngine.Debug.Log(stopwatch.ElapsedTicks);
    }

    void OnGUI()
    {
        if (msg != null) GUILayout.Label(msg);
    }
}

Like in most cases, this time non-unity function seems to be faster. At least on my pc. Don't know how you're app would work, but keep in mind that you can have collisions when using Miliseconds value. There is also one disadvantage of using Time.time - you can do this only in main thread. When you have network application there is high chance you would like to save timestamp on background thread.

like image 116
piotrmitrega Avatar answered Oct 19 '22 03:10

piotrmitrega