简体   繁体   English

用C和linux测量时间

[英]Time measuring in C and linux

I want to see how much is taken by the C program, so I wrote: 我想知道C程序花了多少钱,所以我写道:

  #include<stdio.h>
  #include<stdlib.h>
  #include"memory.h"
  #include"memory_debug.h"
  #include<sys/times.h>
  #include<unistd.h>

  int (*deallocate_ptr)(memContainer *,void*);

  void (*merge_ptr)(node *);

  void* (*allocate_ptr)(memContainer *,unsigned long size);

  memContainer* (*init_ptr)(unsigned long );

  diagStruct* (*diagnose_ptr)(memContainer *);

  void (*finalize_ptr)(memContainer *);

  void (*printNode_ptr)(node *n);

  void (*printContainer_ptr)(memContainer *c);

  void info(memContainer *c)
  {
    struct tms *t;
    t=malloc(sizeof(struct tms));
    times(t);
    printf("user : %d\nsystem : %d\n %d",t->tms_utime,(int)t->tms_stime);
    diagnose_ptr(c);
    printf("\n");
    return ;
  }

but when I invoke this function I get 0 user time and 0 system time, even if I write: 但是当我调用这个函数时,我得到0个用户时间和0个系统时间,即使我写了:

for (i=0;i<100000;++i)
    for (j=0;j<10;++j)
    {}
info(c); 

what am I doing wrong? 我究竟做错了什么?

The compiler probably optimizes away your for loops since they do nothing. 编译器可能会优化你的for循环,因为它们什么都不做。 Try incrementing a volatile variable. 尝试递增volatile变量。

If you only want to know the time, try running time ./app and it will print the cputime, wall clock time etc of the executed app. 如果您只想知道时间,请尝试运行time ./app ,它将打印已执行应用程序的cputime,挂钟时间等。

The code could simply write a volatile variable at the start, put your 'work' in a function (in a separate file), then read the volatile after the 'work' and print something involving the volatile . 代码可以简单地在开始时编写一个volatile变量,将'work'放在一个函数中(在一个单独的文件中),然后在'work'之后读取volatile并打印一些涉及volatile

Or do some simple calculation with a part of the calculation buried in a function, or using a function return. 或者使用隐藏在函数中的部分计算或使用函数返回进行一些简单的计算。

What platform (Operating system & Compiler) are you using? 您使用的是什么平台(操作系统和编译器)?

I don't know what platform you are running on, but there are a few useful questions on stackoverflow about higher precision system clocks. 我不知道你在运行什么平台,但有关高精度系统时钟的stackoverflow有一些有用的问题。 High precision timing in userspace in Linux has several useful links and references. Linux中用户空间的高精度计时有几个有用的链接和参考。

Timing Methods in C++ Under Linux looked useful. C ++中的计时方法在Linux下看起来很有用。

The below demo program outputs nonzero times: 以下演示程序输出非零时间:

#include<stdio.h>
#include<stdlib.h>
#include"memory.h"
#include<sys/times.h>
#include<unistd.h>
#include <iostream>
using namespace std;

int main()
{
    int x = 0;
    for (int i = 0; i < 1 << 30; i++)
        x++;

    struct tms t;
    times(&t);
    cout << t.tms_utime << endl;
    cout << t.tms_stime << endl;
    return x;
}

Output: 输出:

275
1

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

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