Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vala: is this the correct way to get the current time in milliseconds ?

Tags:

vala

Using this library with Vala :

http://valadoc.org/#!api=glib-2.0/GLib.DateTime

    GLib.DateTime now = new GLib.DateTime.now_local();

    var sec = now.to_unix()
    var msec = (sec * 1000) + now.get_microsecond();

is this the correct way to get the current time in millisecond ?

is there a better way ?

like image 219
Max L. Avatar asked Oct 19 '13 15:10

Max L.


1 Answers

GLib.DateTime is a valid way of doing this, and it's a bit weird that you're requesting a local time then converting it to unix time (which implicitly converts to UTC). The real problem, though, is that you're conflating milliseconds (1/1000th of a second) and microseconds (1/1000000th of a second). So change the last line to

var msec = (sec * 1000) + (now.get_microsecond () / 1000);

Alternatively, an easier way would be to use GLib.get_real_time:

int64 msec = GLib.get_real_time () / 1000;

Depending on your use case you might want to consider using monotonic time instead of real time (see GLib.get_monotonic_time

like image 158
nemequ Avatar answered Nov 15 '22 11:11

nemequ