13

Possible Duplicate:
How to measure time in milliseconds using ANSI C?
How can I get the Windows system time with millisecond resolution?

We want to calculate the time which a player have taken to finish the game. But with time.h we could only calculate in seconds. but that is not exact. Is it possible to get the time in milliseconds? and what is the %? to printf?

Community
  • 1
  • 1
kk-dev11
  • 2,654
  • 5
  • 37
  • 48
  • 2
    exact dupilcate http://stackoverflow.com/questions/361363/how-to-measure-time-in-milliseconds-using-ansi-c – niko Dec 19 '11 at 08:19

3 Answers3

20

There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().

Alok Save
  • 202,538
  • 53
  • 430
  • 533
14

quick answer

#include<stdio.h>   
#include<time.h>   

int main()   
{   
    clock_t t1, t2;  
    t1 = clock();   
    int i;
    for(i = 0; i < 1000000; i++)   
    {   
        int x = 90;  
    }   

    t2 = clock();   

    float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;   
    printf("%f",diff);   

    return 0;   
}
Mustafa Ekici
  • 7,263
  • 9
  • 55
  • 75
  • 20
    I thought `clock` yields the cpu time used, not the real time. – cnicutar Dec 19 '11 at 08:20
  • 17
    This code, while possibly correct on some systems, will not always work. You should use CLOCKS_PER_SEC rather than hard-code 1000000. – jarmod Mar 03 '13 at 23:49
  • 1
    @jarmod nice pickup - its required especially on windows under MS VC++ where CLOCKS_PER_SEC is set to 1000. – dodgy_coder Oct 15 '13 at 07:49
  • Shouldn't the answer be changed according to @jarmod comment or at least remove this answer as a correct answer? (@Błażej Michalik) – MikeL Aug 08 '16 at 08:35
1

If you're on a Unix-like system, use gettimeofday and convert the result from microseconds to milliseconds.

jmbr
  • 3,298
  • 23
  • 23