Time stamp in the C programming language

后端 未结 9 1388
别那么骄傲
别那么骄傲 2020-12-08 04:48

How do I stamp two times t1 and t2 and get the difference in milliseconds in C?

相关标签:
9条回答
  • 2020-12-08 05:44

    Use gettimeofday() or better clock_gettime()

    0 讨论(0)
  • 2020-12-08 05:47
    /*
     Returns the current time.
    */
    
    char *time_stamp(){
    
    char *timestamp = (char *)malloc(sizeof(char) * 16);
    time_t ltime;
    ltime=time(NULL);
    struct tm *tm;
    tm=localtime(&ltime);
    
    sprintf(timestamp,"%04d%02d%02d%02d%02d%02d", tm->tm_year+1900, tm->tm_mon, 
        tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
    return timestamp;
    }
    
    
    int main(){
    
    printf(" Timestamp: %s\n",time_stamp());
    return 0;
    
    }
    

    Output: Timestamp: 20110912130940 // 2011 Sep 12 13:09:40

    0 讨论(0)
  • 2020-12-08 05:50

    Standard C99:

    #include <time.h>
    
    time_t t0 = time(0);
    // ...
    time_t t1 = time(0);
    double datetime_diff_ms = difftime(t1, t0) * 1000.;
    
    clock_t c0 = clock();
    // ...
    clock_t c1 = clock();
    double runtime_diff_ms = (c1 - c0) * 1000. / CLOCKS_PER_SEC;
    

    The precision of the types is implementation-defined, ie the datetime difference might only return full seconds.

    0 讨论(0)
提交回复
热议问题