[英]Timing in C with time.h
我在Ubuntu上工作,我想在C中计时一个汇编器函数。
那就是我的代码:
#include <time.h>
#include <stdio.h>
#include <unistd.h>
extern void assembler_function(char*,int);
int main(){
char *text1 = "input.txt";
clock_t start=clock();
sleep(3); // used for test
//assembler_function(text1,0);
clock_t stop=clock();
//printf("%d %f\n",(int)stop,((float)stop)/CLOCKS_PER_SEC);
printf("Time : %f \n",(double)start/CLOCKS_PER_SEC);
printf("Time : %f \n",(double)stop/CLOCKS_PER_SEC);
printf("Time : %f \n",(double)(stop-start)/CLOCKS_PER_SEC);
return 0;
}
结果是:
时间:0.000000
时间:0.000000
时间:0.000000
如果CLOCKS_PER_SEC
的典型值为1000000
,则很可能您正在测量的范围小于一个时钟(1微秒)。 另外,除了clock
本身的开销外, sleep
不会有助于clock
增加,因为clock
测量处理时间,而不是挂钟时间。
相反,请尝试测量执行多次调用汇编器函数所花费的时间,然后将结果除以迭代次数。 如果执行汇编器功能的总时间非常短(例如1ns),则需要对如何执行此操作很聪明,否则循环的开销最终可能成为测量的重要部分。
这是一个在Ubuntu盒子上编译的简单示例:
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <sys/time.h>
#include <unistd.h>
#include <time.h>
int64_t timestamp_now (void)
{
struct timeval tv;
gettimeofday (&tv, NULL);
return (int64_t) tv.tv_sec * CLOCKS_PER_SEC + tv.tv_usec;
}
double timestamp_to_seconds (int64_t timestamp)
{
return timestamp / (double) CLOCKS_PER_SEC;
}
int
main ()
{
int64_t start = timestamp_now ();
sleep (1);
printf ("sleep(1) took %f seconds\n",
timestamp_to_seconds (timestamp_now () - start));
return 0;
}
从有用的man
页上找到clock()
:
描述
The clock() function returns an **approximation of processor time used by the program**.
换句话说, clock()
可能不是您想要的,因为您要计算已用的挂钟时间,而不是CPU使用时间(请注意: sleep()
几乎不使用CPU时间-它只是为将来的起床时间,然后睡...)。
使用difftime:
第一:
time_t t_ini;
t_ini=time(NULL);
在末尾:
difftime((int)time(NULL), (int)t_ini);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.