Measuring time in C and linux
I want to see how much is done 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 call 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?
source to share
Below is a demo program that outputs a non-zero time:
#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
source to share
The code could just write the variable volatile
at the beginning, put its work in a function (in a separate file), then read volatile
after the "work" and print something including volatile
.
Or, do a simple calculation with the calculation part buried in a function, or using the return function.
What platform (operating system and compiler) are you using?
I don't know what platform you are on, but there are some helpful stackoverflow questions about high precision system clock. High fidelity user space synchronization in Linux contains several useful links and references.
Synchronization techniques in C ++ under Linux looked useful.
source to share