2013-06-22 45 views
6

我在网上搜索过,但我只找到了一个办法,但以这种方式它返回的秒数而不是毫秒。如何获得以毫秒为单位的C所花费的时间? (Windows)

我的代码是:

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

int main(void) 
{ 
    int solucion; 

    time_t start, stop; 
    clock_t ticks; 
    long count; 

    time(&start); 
    solucion = divisores_it(92000000, 2); 
    time(&stop); 

    printf("Finnished in %f seconds. \n", difftime(stop, start)); 
    return 0; 
} 

回答

20

跨平台的方式是使用ftime。

Windows特定链接的位置:下方http://msdn.microsoft.com/en-us/library/aa297926(v=vs.60).aspx

例。

#include <stdio.h> 
#include <sys\timeb.h> 

int main()  
{ 
    struct timeb start, end; 
    int diff; 
    int i = 0; 
    ftime(&start); 

    while(i++ < 999) { 
     /* do something which takes some time */ 
     printf(".");  
    } 

    ftime(&end); 
    diff = (int) (1000.0 * (end.time - start.time) 
     + (end.millitm - start.millitm)); 

    printf("\nOperation took %u milliseconds\n", diff); 
    return 0; 
} 

我跑了上面的代码,并使用VS2008通过它追踪,看到它实际上调用Windows GetSystemTimeAsFileTime功能。

无论如何,ftime会给你毫秒的精度。

+0

根据http://man7.org/linux/man-pages/man3/ftime.3.html,ftime()已过时。也许更好的跨平台解决方案是使用['std :: chrono'](http://en.cppreference.com/w/cpp/chrono)库。 – erobertc

+4

@erobertc OP需要一个'C'解决方案,而不是'C++'。你的建议需要'C++'。 – rbaleksandar

1

对于Windows,GetSystemTime()是你想要的。对于POSIX,gettimeofday()

9

下面的解决方案似乎对我很好。你怎么看?

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

long timediff(clock_t t1, clock_t t2) { 
    long elapsed; 
    elapsed = ((double)t2 - t1)/CLOCKS_PER_SEC * 1000; 
    return elapsed; 
} 

int main(void) { 
    clock_t t1, t2; 
    int i; 
    float x = 2.7182; 
    long elapsed; 

    t1 = clock(); 
    for (i=0; i < 1000000; i++) { 
      x = x * 3.1415; 
    } 
    t2 = clock(); 

    elapsed = timediff(t1, t2); 
    printf("elapsed: %ld ms\n", elapsed); 


    return 0; 
} 

参考:http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.15.html#clock

+0

您不能在此行使用'timediff':'elapsed = timediff(t1,t2);' 除非定义了正确的头文件。 只是't2-t1'会正常工作。 – inckka

+1

@inckka,'timediff()'定义在'main()'的正上方。不需要头文件。而't2-t1'不会以毫秒为单位给出答案。 – mcrisc

+0

你是对的。对不小心的误会抱歉。 – inckka

0

此代码块的工作。这是基于安格斯精梳机的回答:

#include <sys/timeb.h> 

uint64_t system_current_time_millis() 
{ 
#if defined(_WIN32) || defined(_WIN64) 
    struct _timeb timebuffer; 
    _ftime(&timebuffer); 
    return (uint64_t)(((timebuffer.time * 1000) + timebuffer.millitm)); 
#else 
    struct timeb timebuffer; 
    ftime(&timebuffer); 
    return (uint64_t)(((timebuffer.time * 1000) + timebuffer.millitm)); 
#endif 
} 
相关问题