【问题标题】:Timing in C with time.h用 time.h 在 C 中计时
【发布时间】:2015-08-18 01:30:24
【问题描述】:

我在 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

【问题讨论】:

    标签: c time time.h


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 虽然正确,但缺乏解释限制了教育价值。目前尚不清楚为什么这个解决方案更好。可以通过确定问题所在(clock 中缺乏解决方案,以及其功能适用性——用户时间与挂钟时间)以及如何解决这些问题来改进它。
      【解决方案3】:

      来自有用的man-页面clock()

      描述

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

      换句话说,clock() 可能不是您想要的,因为您想计算经过的挂钟时间,而不是 CPU 使用时间(注意:sleep() 几乎不使用 CPU 时间 - 它只是设置一个为将来的起床时间设置闹钟,然后,嗯,睡觉......)。

      【讨论】:

        【解决方案4】:

        使用差异时间:

        第一:

        time_t t_ini;
        t_ini=time(NULL);
        

        最后:

        difftime((int)time(NULL), (int)t_ini);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-10-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-06
          • 1970-01-01
          相关资源
          最近更新 更多