Reputation: 6689
I want to see how much is taken by the C program, so I wrote:
#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:
for (i=0;i<100000;++i)
for (j=0;j<10;++j)
{}
info(c);
what am I doing wrong?
Upvotes: 3
Views: 423
Reputation: 68738
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
Upvotes: 1
Reputation: 4290
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
.
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. High precision timing in userspace in Linux has several useful links and references.
Timing Methods in C++ Under Linux looked useful.
Upvotes: 2
Reputation: 2066
The compiler probably optimizes away your for
loops since they do nothing. Try incrementing a volatile
variable.
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.
Upvotes: 3