How to get the current time in milliseconds in C Programming [duplicate]
Asked Answered
F

3

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?

Flori answered 19/12, 2011 at 8:13 Comment(1)
exact dupilcate #361863Holdover
M
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;   
}
Medeah answered 19/12, 2011 at 8:16 Comment(4)
I thought clock yields the cpu time used, not the real time.Klingel
This code, while possibly correct on some systems, will not always work. You should use CLOCKS_PER_SEC rather than hard-code 1000000.Danley
@Danley nice pickup - its required especially on windows under MS VC++ where CLOCKS_PER_SEC is set to 1000.Perception
Shouldn't the answer be changed according to @Danley comment or at least remove this answer as a correct answer? (@Błażej Michalik)Debidebilitate
C
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().

Covetous answered 19/12, 2011 at 8:16 Comment(1)
On Windows, you could also GetTickCount ().Maibach
M
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;   
}
Medeah answered 19/12, 2011 at 8:16 Comment(4)
I thought clock yields the cpu time used, not the real time.Klingel
This code, while possibly correct on some systems, will not always work. You should use CLOCKS_PER_SEC rather than hard-code 1000000.Danley
@Danley nice pickup - its required especially on windows under MS VC++ where CLOCKS_PER_SEC is set to 1000.Perception
Shouldn't the answer be changed according to @Danley comment or at least remove this answer as a correct answer? (@Błażej Michalik)Debidebilitate
S
1

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

Shiller answered 19/12, 2011 at 8:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.