繁体   English   中英

Linux C中的时间返回值0

[英]Times return value 0 in Linux C

我开始学习Linux C,但是遇到了这个问题,我很困惑。
我使用函数times但返回的值等于0。
好的,我做了错了,我更改了代码:但是与printf的关系并不多。 clock_t是在Linux.long中定义的,因此我将clock_t转换为long。
这是我的代码:

#include <sys/times.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
   long clock_times;
   struct tms begintime;
   sleep(5);
   if((clock_times=times(&begintime))==-1)
      perror("get times error");
   else
   {
      printf("%ld\n",(long)begintime.tms_utime);
      printf("%ld\n",(long)begintime.tms_stime);
      printf("%ld\n",(long)begintime.tms_cutime);
      printf("%ld\n",(long)begintime.tms_cstime);
   }
   return 0;
}

输出:0 0 0 0
也返回0;
我使用gdb进行调试,begintimes的变量也为零。 printf函数没有亲戚。

您的代码几乎没有使用CPU时间,因此结果是正确的。 睡眠会暂停您的程序执行-这段时间内发生的所有事情都不是您的执行时间,因此不会被计入。

添加空循环,您将看到区别。 (当然,请禁用编译器优化-否则将删除空循环)。

看一下“时间”程序的输出(时间./a.out)-它显示“实际”时间(我想是由gettimeofday()估计),用户时间(由用户空间代码浪费的时间)和系统时间(时间)在系统调用中浪费-例如写入文件,打开网络连接等)。

(当然,“浪费”是指“二手”,但无论如何)

这并不罕见。 该过程根本没有使用足够的CPU时间来衡量。 进程花费在sleep()上的时间不计入程序的CPU时间,因为times()度量的是执行用户指令所收取的CPU时间 (以及其他相关时间),它是进程的时间花了执行用户/内核代码。

将程序更改为以下程序,它将使用更多的CPU,因此可以进行测量:

#include <sys/times.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
   long clock_times;
   struct tms begintime;
   unsigned i;

   for (i = 0; i < 1000000; i++)
      time(NULL);    // An arbitrary library call

   if((clock_times=times(&begintime))==-1)
      perror("get times error");
   else
   {
      printf("%ld %ld %ld %ld\n",
        (long)begintime.tms_utime,
        (long)begintime.tms_stime,
        (long)begintime.tms_cutime,
        (long)begintime.tms_cstime);
   }
   return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM