如何得知某段代码的运行时间

12 篇文章 0 订阅
    转自:http://blog.chinaunix.net/uid-27034868-id-3371737.html     
    之前,我的同学问了我一个算法题,由于这个题是要通过提交代码然后在线测试的,有运行时间的限制。我想应该有办法把某段代码的运行时间计算出来,当然现在某些IDE(集成开发环境)已经提供了这个功能,但是我猜它只是计算进程开始至结束的时间,如果我们需要更精确,精确到某段代码的运行时间的话,我们可以在代码中加入相应的代码就可以得到这个运行时间了。很多时候可以用于比较两(几)个算法的效率。
 
    下面给出两个比较方便的方法在C语言中的使用(C++的更多本文不讨论)

点击(此处)折叠或打开

  1. // count_time.c

  2. // 求2000000内素数和,并计算所用时间(精确)
  3. #include <stdio.h>
  4. #include <math.h>
  5. #include <sys/time.h> // struct timeval 的定义
  6. #include <time.h> // clock的定义

  7. void prime_number()
  8. {
  9.     unsigned long m, k, i;//, n = 0;
  10.     unsigned long sum = 0;

  11.     printf("2000000内素数和为:\n");
  12.     for (= 3; m < 2000000;+= 2) {
  13.         k = (unsigned long)sqrt(m);
  14.         for (= 2; i <= k; i++) {
  15.             if (% i == 0)
  16.                 break;
  17.         }
  18.         if (>= k + 1)
  19.             sum += m;
  20.     }
  21.     printf("sum= %lld\n",sum+2);
  22. }

  23. // 计时方法一( 在Unix/Linux下使用)
  24. void count_runtime1()
  25. {
  26.     struct timeval start, end;

  27.     gettimeofday( &start, NULL );//第二个参数不为空则用于返回时区结果,这里不需要

  28.     //* 在start与end之间运行需要计时的代码 
  29.     prime_number();
  30.     
  31.     gettimeofday( &end, NULL );
  32.     
  33.     unsigned int timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + \
  34.                 end.tv_usec -start.tv_usec;
  35.                          
  36.     printf("timeuse: %d us(微妙)\n", timeuse);
  37. }

  38. // 计时方法2
  39. void count_runtime2()
  40. {
  41.     
  42.     /* 使用下面的clock获取,更接近cpu运行时间 ,标准C更通用*/
  43.     clock_t clock_start = clock();
  44.     
  45.     prime_number();// 需要计时的代码
  46.     
  47.     clock_t clock_end = clock();
  48.     
  49.     printf("timesue: %ld us\n", clock_end - clock_start);
  50. }

  51. int main()
  52. {
  53.     count_runtime1();
  54.     count_runtime2();
  55.     
  56.     return 0;
  57. }
  58. /******************************************************************************/
  59. /* man 手册中对gettimeofday函数的说明:
  60. NAME
  61.        gettimeofday, settimeofday - get / set time

  62. SYNOPSIS
  63.        #include <sys/time.h>

  64.        int gettimeofday(struct timeval *tv, struct timezone *tz);
  65.        int settimeofday(const struct timeval *tv, const struct timezone *tz);

  66.    Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

  67.        settimeofday(): _BSD_SOURCE

  68. DESCRIPTION
  69.        The functions gettimeofday() and settimeofday() can get and set      the time as well as a timezone. The tv argument is a struct          meval (as specified in <sys/time.h>):

  70.            struct timeval {
  71.                time_t tv_sec; // seconds 
  72.                suseconds_t tv_usec; // microseconds 
  73.            };
  74.   …………
  75.   RETURN VALUE
  76.        gettimeofday() and settimeofday() return 0 for success, or -for fail?br />
  77.        ure (in which case errno is set appropriately).

  78. ***************************************************************************************/

  79. /* man 手册中对clock函数的说明:
  80. NAME
  81.        clock - Determine processor time

  82. SYNOPSIS
  83.        #include <time.h>

  84.        clock_t clock(void);

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

  87. RETURN VALUE
  88.        The value returned is the CPU time used so far as a clock_t; to get      the number of seconds used, divide by CLOCKS_PER_SEC. If the      processor time used is not available or its value cannot be      represented, the
  89.        function returns the value (clock_t) -1.

  90. CONFORMING TO
  91.        C89, C99, POSIX.1-2001. POSIX requires that CLOCKS_PER_SEC equals
  92.        1000000 independent of the actual resolution.
  93.        int /usr/include/time.h #define CLOCKS_PER_SEC 1000000l

  94. NOTES
  95.        The C standard allows for arbitrary values at the start of the program;subtract the value returned from a call to clock() at the      start of the program to get maximum portability.
  96. ……
  97. ******************************************************************************/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用计时器来测量代码段的运行时间。具体步骤如下: 1. 在代码段前启动计时器。 2. 在代码段后停止计时器。 3. 通过计时器的计数器值计算代码段的运行时间。 例如,如果您使用的是GD32F450ZIT6上的定时器2,您可以按照以下步骤进行操作: ```c #include "gd32f4xx.h" // 启动计时器 void start_timer() { // 使能定时器2的时钟 rcu_periph_clock_enable(RCU_TIMER2); // 配置定时器2的基本参数 timer_parameter_struct timer_initpara; timer_struct_para_init(&timer_initpara); timer_initpara.prescaler = 10800 - 1; // 时钟分频系数 timer_initpara.period = 0xFFFF; // 自动重载值 timer_initpara.clock_division = TIMER_CKDIV_DIV1; // 时钟分频因子 timer_initpara.counter_mode = TIMER_COUNTER_UP; // 计数器向上计数模式 timer_initpara.repetition_counter = 0; // 重复计数器值 timer_init(TIMER2, &timer_initpara); // 启动定时器2 timer_enable(TIMER2); } // 停止计时器,并返回计时器计数器的值 uint32_t stop_timer() { // 停止定时器2 timer_disable(TIMER2); // 获取计数器的值 return timer_value(TIMER2); } // 测试代码 void test_code() { // 启动计时器 start_timer(); // 运行代码段 // ... // 停止计时器,并输出运行时间 uint32_t count = stop_timer(); float time = (float)count / 108000000.0f; // 将计数器转换为秒 printf("代码运行时间为 %f 秒\n", time); } ``` 需要注意的是,如果您的代码运行时间非常短,计时器的计数器值可能会溢出。在这种情况下,您需要使用更高分辨率的计时器或增加计时器的时钟分频系数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值