From milliseconds to hour, minutes, seconds and milliseconds

前端 未结 9 1834
失恋的感觉
失恋的感觉 2020-12-07 21:22

I need to go from milliseconds to a tuple of (hour, minutes, seconds, milliseconds) representing the same amount of time. E.g.:

10799999ms = 2h 59m 59s 999ms

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 21:36

    Good question. Yes, one can do this more efficiently. Your CPU can extract both the quotient and the remainder of the ratio of two integers in a single operation. In , the function that exposes this CPU operation is called div(). In your psuedocode, you'd use it something like this:

    function to_tuple(x):
        qr = div(x, 1000)
        ms = qr.rem
        qr = div(qr.quot, 60)
        s  = qr.rem
        qr = div(qr.quot, 60)
        m  = qr.rem
        h  = qr.quot
    

    A less efficient answer would use the / and % operators separately. However, if you need both quotient and remainder, anyway, then you might as well call the more efficient div().

提交回复
热议问题