发布日期:2018-03-26
如何计算C++中片段代码的执行时间?+ 查看更多
如何计算C++中片段代码的执行时间?
+ 查看更多
发布日期:2018-02-26 13:59
分类:CPlusPlus
浏览次数:93
我必须在很快的时间内计算出C++中片段代码的执行时间。这个方法必须在Windows或者Unix机器上运行。
我用以下的代码来计算片段代码的执行时间(之前导入的)
clock_t startTime = clock(); // some code here // to compute its execution duration in runtime cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
然而对于特别小的输入或者短语句,如a=a+1,我得到的是“0秒”的结果。我认为这一定是时间是0.0000001秒或者类似的情况。
我记得在Java中的System.nanoTime()在这种情况下可以工作的很好。但是我却不能从C++中的clock()获得如此准确的功能?
请问您有解决方案吗?
回答
你可以使用我写的这个函数。你调用GetTimeMs64()这个函数,它使用系统时钟返回自从unix纪元过去的毫秒数,就像time(NULL)一样,除非时间是在毫秒以内。
这个方法在Windows和Linux上都可以用,是线程安全的。
注意Windows上的粒度是15ms;在Linux上是依赖于实现方式的,但一般也是15ms。
#ifdef _WIN32 #include#else #include #include #endif /* Remove if already defined */ typedef long long int64; typedef unsigned long long uint64; /* Returns the amount of milliseconds elapsed since the UNIX epoch. Works on both * windows and linux. */ uint64 GetTimeMs64() { #ifdef _WIN32 /* Windows */ FILETIME ft; LARGE_INTEGER li; /* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it * to a LARGE_INTEGER structure. */ GetSystemTimeAsFileTime(&ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; uint64 ret = li.QuadPart; ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */ ret /= 10000; /* From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals */ return ret; #else /* Linux */ struct timeval tv; gettimeofday(&tv, NULL); uint64 ret = tv.tv_usec; /* Convert from micro seconds (10^-6) to milliseconds (10^-3) */ ret /= 1000; /* Adds the seconds (10^0) after converting them to milliseconds (10^-3) */ ret += (tv.tv_sec * 1000); return ret; #endif }