Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Time.realtimeSinceStartup and System Time do not match in RuntimeInitializeOnLoadMethod

Discussion in 'Scripting' started by TCYeh, Jul 26, 2023.

  1. TCYeh

    TCYeh

    Joined:
    Jul 25, 2022
    Posts:
    51
    Hello,

    I noticed that Time.realtimeSinceStartup does not match the system time when used in RuntimeInitializeOnLoadMethod.

    Below is a diagram showing the timestamps I printed using DateTime.Now and Time.realtimeSinceStartup. The time gap between BeforeSplashScreen and Awake is 1.9511063 for Time.realtimeSinceStartup and 2.055 for the system time.
    time.png

    As the reference, here is how I log the time:
    Code (CSharp):
    1.  [{DateTime.Now.ToString("HH:mm:ss.FFF")}] BeforeSplashScreen: {Time.realtimeSinceStartup}
    According to the documentation, Time.realtimeSinceStartup should obtain its value from the system time. Therefore, it should not have an offset with the system time (DateTime.Now), right?

    This discrepancy only occurs in RuntimeInitializeOnLoadMethod, while other lifecycle methods behave correctly.

    Is this a bug, or am I missing something?

    Thank you in advance.
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    3,899
    You are missing the crucial letter ‚r‘ here. It takes time from the system time*r*. ;)

    Nothing states that DateTime uses that same timer. In fact I think it relies on the OS timer. There are specific high performance timer (counter) to measure accurate sub-millisecond times which DateTime does not do.
     
    TCYeh likes this.
  3. rdjadu

    rdjadu

    Joined:
    May 9, 2022
    Posts:
    102
    realtimeSinceStartup is set to 0 at a certain point in Unity's startup sequence. The value it uses differs from platform to platform. On Windows it uses QueryPerformanceCounter converted from ticks to seconds.

    So yeah, as @CodeSmile says, no direct correlation to DateTime/system time. There's no API to tell you what the system time was when Unity set realtimeSinceStartup to 0. It just counts the second that the Unity app has been running (counting from somewhere *within* its startup sequence).
     
    TCYeh likes this.