使用clock()来测量执行时间
我正在运行一个使用GCC和专有DSP交叉编译器的C程序来模拟一些function。 我使用以下代码来测量程序特定部分的执行时间:
clock_t start,end; printf("DECODING DATA:\n"); start=clock(); conv3_dec(encoded, decoded,3*length,0); end=clock(); duration = (double)(end - start) / CLOCKS_PER_SEC; printf("DECODING TIME = %f\n",duration);
其中conv3_dec()
是我的程序中定义的函数,我想找到这个函数的运行时。
现在问题是我的程序运行时, conv3_dec()
函数运行了近2个小时,但printf("DECODING TIME = %f\n",duration)
的输出printf("DECODING TIME = %f\n",duration)
表示函数的执行只完成了半个第二( DECODING TIME = 0.455443
)。 这对我来说非常困惑。
我之前使用clock_t
技术来测量程序的运行时间,但差异从未如此巨大。 这是由交叉编译器引起的吗? 正如旁注所示,模拟器模拟仅以500MHz运行的DSP处理器,因此DSP处理器和CPU的时钟速度差异导致错误正在测量CLOCKS_PER_SEC。
对于两个小时的持续时间,我不会太关心clock()
,它对于测量亚秒持续时间更有用。
如果你想要实际的经过时间,请使用time()
,例如(为缺少的东西提供的虚拟东西):
#include #include // Dummy stuff starts here #include #define encoded 0 #define decoded 0 #define length 0 static void conv3_dec (int a, int b, int c, int d) { sleep (20); } // Dummy stuff ends here int main (void) { time_t start, end, duration; puts ("DECODING DATA:"); start = time (0); conv3_dec (encoded, decoded, 3 * length, 0); end = time (0); duration = end - start; printf ("DECODING TIME = %d\n", duration); return 0; }
产生:
DECODING DATA: DECODING TIME = 20
clock
测量cpu时间而不是wallclock时间。 由于您没有在cpu上运行大部分代码,因此这不是正确的工具。
gettimeofday()
函数也可以考虑。
gettimeofday()函数应获取当前时间,表示为自Epoch以来的秒和微秒,并将其存储在tp指向的timeval结构中。 系统时钟的分辨率未指定。
计算C程序中的已用时间(以毫秒为单位)