我在网上搜索过,但我只是找到了一种方法,但这样就会以秒为单位而不是毫秒。
我的代码是:
#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;
}
答案 0 :(得分:24)
跨平台的方式是使用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会给你毫秒精度。
答案 1 :(得分: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
答案 2 :(得分:2)
对于Windows,GetSystemTime()
是您想要的。对于POSIX,gettimeofday()
。
答案 3 :(得分:1)
GetSystemTime()
使用结构SYSTEMTIME
,它提供毫秒级的分辨率。
答案 4 :(得分:1)
此代码段有效。这是基于Angus Comber的回答:
#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
}
答案 5 :(得分:0)
DWORD start = GetTickCount();
executeSmth();
printf("Elapsed: %i ms", GetTickCount() - start);
P.S。此方法有一些限制。参见GetTickCount。