LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 932|回复: 3

如何计算程序中一个作业的时间?

[复制链接]
发表于 2008-7-6 15:36:01 | 显示全部楼层 |阅读模式
我最近在做一个小程序
  以 ANSI C 作为语言核心,实现常见各种内部排序算法,提供简单操作接口,让用户可以直观了解各
  算法原理、性能、时空复杂度。

怎么算独立算各个排序作业的时间?

我想到的是
  1. time_t s, e;
  2. s = time(0);
  3. sort();
  4. e = time(0);
  5. printf("\n %f ", difftime(e, s));
复制代码
但是,很显示,我的做法是错误的。

  1. lee@lee-thinkpad:$ time ./bubble_selection
  2. real        0m1.835s
  3. user        0m0.008s
  4. sys        0m0.012s
复制代码

real 时间似乎就是我想要的
发表于 2008-7-7 09:40:43 | 显示全部楼层
如果楼主手边没有一本 unix 编程的基础教程, 而又想知道一个已有的功能如何实现的话, 那么可以用这样的方法来找到实现此功能可能需要的接口函数. 以 time 命令为例, 它是如何工作的呢?
  1. ltrace time true 2> log
复制代码
然后看看 log 里面都调用了哪些函数, 不明白的就 man 一下, 见到 man 中有趣的 see also 也跟过去看看, 很快就知道自己需要的是什么了.

关于 ltrace 请自行 man ltrace

如果系统中没有 ltrace 的话, 那么试试 strace, 这个并不像 ltrace 那么适合于这种用途, 但是也能用. 如果二者都没有的话, 建议装一份, 很有用的
回复 支持 反对

使用道具 举报

 楼主| 发表于 2008-7-7 18:54:40 | 显示全部楼层
谢谢。

不过我已经找到一个临时方案了。


  1. #include <sys/time.h>
  2. #include <stdio.h>
  3. #include <math.h>
  4. #include "funcs.h"

  5. /*
  6. struct timeval
  7. {
  8.   long tv_sec;
  9.   long tv_usec;
  10. };
  11. */

  12. //gettimeofday把时间保存在结构tv之中.tz一般我们使用NULL来代替.

  13. int gettimeofday(struct timeval *tv, struct timezone *tz);

  14. void function()
  15. {
  16.         unsigned int i, j;
  17.         double y;
  18.        
  19.         for(i = 0; i < 1000; i++)
  20.                 for(j = 0; j < 1000; j++)
  21.                         y = sin( (double)i );
  22. }


  23. int main()
  24. {
  25.         struct timeval tpstart, tpend;
  26.         float timeuse;
  27.        
  28.         gettimeofday(&tpstart, NULL);
  29.        
  30.         //function();
  31.         si();
  32.        
  33.         gettimeofday(&tpend, NULL);
  34.        
  35.         timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;
  36.        
  37.         timeuse /= 1000000;
  38.        
  39.         printf(" Used Time:%f \n", timeuse);
  40.        
  41.        
  42.         gettimeofday(&tpstart, NULL);
  43.        
  44.         //function();
  45.         bs();
  46.        
  47.         gettimeofday(&tpend, NULL);
  48.        
  49.         timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;
  50.        
  51.         timeuse /= 1000000;
  52.        
  53.         printf(" Used Time:%f \n", timeuse);
  54.        
  55.         return 0;
  56. }
复制代码


我知道有很好的书,不过,我太懒了。
回复 支持 反对

使用道具 举报

发表于 2008-7-14 23:00:22 | 显示全部楼层
赞同remote fish 的方案。不过linux进程应该本来就有三种计时器就像time命令显示的一样。好像是同一函数使用了不同的选项返回了不同的时钟。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表