How to get the current time in milliseconds from C in Linux?

前端 未结 7 919
不知归路
不知归路 2020-11-30 19:09

How do I get the current time on Linux in milliseconds?

7条回答
  •  旧巷少年郎
    2020-11-30 19:48

    Following is the util function to get current timestamp in milliseconds:

    #include 
    
    long long current_timestamp() {
        struct timeval te; 
        gettimeofday(&te, NULL); // get current time
        long long milliseconds = te.tv_sec*1000LL + te.tv_usec/1000; // calculate milliseconds
        // printf("milliseconds: %lld\n", milliseconds);
        return milliseconds;
    }
    

    About timezone:

    gettimeofday() support to specify timezone, I use NULL, which ignore the timezone, but you can specify a timezone, if need.


    @Update - timezone

    Since the long representation of time is not relevant to or effected by timezone itself, so setting tz param of gettimeofday() is not necessary, since it won't make any difference.

    And, according to man page of gettimeofday(), the use of the timezone structure is obsolete, thus the tz argument should normally be specified as NULL, for details please check the man page.

提交回复
热议问题