Ubuntu下的clock()问题

laciqs 2010-08-27 07:47:32
#include <stdio.h>
#include <time.h>

int main(void)
{
int num;

scanf("%d", &num);
printf("%d\n", num);
printf("Time used = %.2f\n", (double)clock() / CLOCKS_PER_SEC);
return 0;
}

这个程序在Ubuntu 10.04下的Time used总是为0,而在Windows下却正常。
我也查了man page,但没有得到解决这个问题的相关信息,也许是本人愚笨没看出其中深意。
...全文
551 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
laciqs 2010-08-27
  • 打赏
  • 举报
回复
不过Windows下输入时间也算了,不知道为什么,恩。
laciqs 2010-08-27
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 kingteng 的回复:]

C/C++ code

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

The value returned is the CPU time used so far as a clock_t; to get the number of seco……
[/Quote]
活生生的就一个悲剧,虽然我也看到man page那些内容了,但我由于不知道CPU时间是什么以及过于信任某书内容就没注意,之前循环看来设置的迭代次数太少就没看出来(而且感觉Linux下结果为0.00的频率比Windows高),所以以为是什么特别的问题。
刚才迭代次数设置高了就有结果了,看来还是应该像你一样多看man page少信根据不大的书,非常感谢!
kingteng 2010-08-27
  • 打赏
  • 举报
回复

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

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 function returns the value (clock_t)-1.

注意是CPU时间,不是程序执行总共花的时间,所以你手动输入的时间应该是不计入的,也就是处理时间太短,几乎为0
laciqs 2010-08-27
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 bobo364 的回复:]

楼主想搞个程序运行计时程序?
C/C++ code
#include <stdio.h>
#include <time.h>

int main(void)
{
int num;

scanf("%d", &num);
printf("%d\n", num);
printf("Time used = %.2f\n", (double)clock() / CLOCKS_PER_SEC)……
[/Quote]
你的程序和我的没什么区别,并不是说没暂停程序结果就是0,而且你还忘了<stdlib.h>而且pause是Windows下命令提示符命令,在Linux上无效。
bobo364 2010-08-27
  • 打赏
  • 举报
回复
楼主想搞个程序运行计时程序?
#include <stdio.h>
#include <time.h>

int main(void)
{
int num;

scanf("%d", &num);
printf("%d\n", num);
printf("Time used = %.2f\n", (double)clock() / CLOCKS_PER_SEC);
system("pause");
return 0;
}
laciqs 2010-08-27
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 kingteng 的回复:]

时间太短了吧,你循环一段时间看看
[/Quote]
1. clock()会把输入等待时间也计入,所以几乎我只要手动输入数据,时间都不会短。
2. 在Windows下正常,这也大概说明时间应该不短且我的输出格式是保留两位小数的。
kingteng 2010-08-27
  • 打赏
  • 举报
回复
时间太短了吧,你循环一段时间看看
laciqs 2010-08-27
  • 打赏
  • 举报
回复
另外在CentOS中测试亦如此。

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧