如何以毫秒为单位获得以C为单位的时间? (视窗)

我在网上搜索过但我只找到了一种方法,但这样它就会以秒为单位而不是几毫秒。

我的代码是:

#include  #include  #include  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; } 

跨平台的方式是使用ftime。

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

以下示例。

 #include  #include  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会给你几毫秒的精度。

以下解决方案对我来说似乎没问题。 你怎么看?

 #include  #include  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

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

GetSystemTime()使用SYSTEMTIME结构,它提供毫秒级的分辨率。

更多关于这里 。

这段代码有效。 这是基于Angus Comber的答案:

 #include  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 }