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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With