RE: timing functions and chunks of code in *nix?

  • From: Delaunay Christophe <christophe.delaunay@xxxxxxxxxxxxxxx>
  • To: "programmingblind@xxxxxxxxxxxxx" <programmingblind@xxxxxxxxxxxxx>
  • Date: Tue, 8 Feb 2011 18:02:36 +0100

Hi Tyler,

According to the pieces of code you put in this message, I'm assuming you are 
programming in a C-like language: C or C++, it does not matter, or just little. 
Am I right?

So, here we go. The lines of C code are extracted from a library I made to do 
this, but for logging purposes. The time measurement function I'm using is a 
low-precision one, measuring time at a millisecond roundtrip or so.

On top of the logger module, I need the following line:

#include <sys/time.h>

This header contains the "timeval" data structure definition and the 
"gettimeofday()" system call definition I'm using then.

Then, I need two data structures of type "timeval".

struct timeval prev, now; /* time of day with low precision, (expressed in s+µs 
but rounded to ms) */
int val; /* used to compute a number of milliseconds */

In linux, your instruction "prev=gettime()" reads as:

gettimeofday(&prev, NULL);

then, you would have

myfunction();

as you did in your code.

Then,

gettimeofday(&now, NULL);
val = (now.tv_sec-prev.tv_sec)*1000 /* whole seconds if any multiplied by 1000 
to get ms */
        + (int)((now.tv_usec-prev.tv_usec)/1000); /* number of µs from which I 
compute integer division by 1000 to get ms */

and finally

printf("It took you %d milliseconds",val);

Apart from syntax errors I did not check since my linux box is off right now.

For more info, please have a look to

man gettimeofday

HTH. Have a nice day. Chris D

-----Original Message-----
From: programmingblind-bounce@xxxxxxxxxxxxx 
[mailto:programmingblind-bounce@xxxxxxxxxxxxx] On Behalf Of Littlefield, Tyler
Sent: mardi 8 février 2011 16:57
To: programmingblind@xxxxxxxxxxxxx
Subject: timing functions and chunks of code in *nix?

Hello all,
I know windows exposes high-resolution timers to do this sorta thing, 
but I'm curious how I could do the same in Linux? Is there something 
that will give me timing in ms? so:
prev = gettime();
myfunc();
now = gettime();
printf("you spent %d ms.\n", prev-now);

-- 

Thanks,
Ty
__________
View the list's information and change your settings at
//www.freelists.org/list/programmingblind

Other related posts: