用time.h在C中计时

时间:2015-06-03 17:29:18

标签: c time 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

4 个答案:

答案 0 :(得分:1)

如果CLOCKS_PER_SEC1000000的典型值,那么您测量的范围完全可能小于一个时钟(1微秒)。此外,sleep除了调用本身的开销外,不会对clock的增加做出贡献,因为clock会测量处理时间,而不是挂钟时间。

相反,尝试测量执行对汇编程序函数的多次调用所花费的时间,然后将结果除以迭代次数。如果执行汇编程序功能的总时间非常短(例如1ns),那么您需要巧妙地了解如何执行此操作,否则循环的开销可能最终成为测量的重要部分。

答案 1 :(得分:0)

这是一个简单的例子,在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;
}

答案 2 :(得分:0)

man的有用clock()页面:

  

说明

   The clock() function returns an **approximation of processor time used by the program**.

换句话说,clock()可能不是你想要的,因为你想计算过去的挂钟时间,而不是CPU使用时间(注意:sleep()几乎没有CPU时间 - 它只会为将来的唤醒时间设置一个警报,然后,睡觉......)。

答案 3 :(得分:0)

使用difftime:

首先:

layout.show(nf)
par(mar = c(3, 3, 1, 1)) # <-- Here
plot(x, y, xlim = xrange, ylim = yrange, xlab = 'Hello X-axis', ylab = 'Hello Y-axis', 
     ...)

最后:

time_t t_ini;
t_ini=time(NULL);