[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: need time in nano seconds



On Mon, 2004-12-13 at 19:59 +0530, Micheal Mukherji wrote:
> Hello,
> Kindly excuse me for posting this on debian thread...I dont know
> whether it is apt or not, but as I am using Debian, I am posting
> this..
> 
> Can somebody tell me how I can get time elapsed in nanoseconds
> (possibly a function)?
> I have looked at the date command, but it is getting overflown with in
> a couple of seconds, so on a second probe I dont know how many times
> it has overflown...
> 
> I also googled for it, but all it was showing was links to RTLinux pages.
> 
> Having got dismayed, I am posting on this list.
> 
> If somebody knows, please let me too.
> 

It is impossible without realtime patches applied. In 2.4, Hz is set at
100 giving you a granularity of 10ms. In 2.6, Hz was changed to 1000
giving you a granularity of 1ms.

In other words the timer interrupt pops every 1ms making it impossible
to accurately measure down to the nanosecond. There are kernel patches
in the works that provide dynamic Hz. There are also realtime patches
from Monta Vista but even those don't get down to the nanosecond range.

Windows uses a special register on the CPU but even the reading of the
register takes longer than a nanosecond (in fact the CPU itself is only
able to update this value at about every 800 nanoseconds). Linux runs on
too many architectures for this to be a feasible solution.

There are some system calls that try to calculate down to the nanosecond
but be assured that this is only a mathematical calculation and is NOT
truly accurate.

Here is a simple set of macros I use to time algorithms for an algorithm
analysis class. These macros estimate down to the nanosecond but that's
as good as it gets.

#ifndef _NTIME_H
#define _NTIME_H

#include <time.h>
#include <linux/types.h>

static struct timespec _tstart, _tend;

__u64   t1, t2;

#define START() \
	        clock_gettime(CLOCK_REALTIME, &_tstart)
#define STOP()  \
	        clock_gettime(CLOCK_REALTIME, &_tend)

#define VALUE()                                                                 \
	        t1 =  (__u64)((__u64)(_tstart.tv_sec)*(100000*10000)) + (__u64)_tstart.tv_nsec; \
        	t2 =  (__u64)((__u64)(_tend.tv_sec)*(100000*10000)) + (__u64)_tend.tv_nsec;     \
        	printf("%lld\n", (t2-t1));

#define timer(action) action()

#endif


To use this just compile and link against librt...

]$ gcc main.c -o main -lrt

Include this header file and wrap your code in it like such...

timer(START)
	my timed code ...
timer(STOP)
timer(VALUE)

-- 
Eric Gaumer <gaumerel@ecs.fullerton.edu>

Attachment: signature.asc
Description: This is a digitally signed message part


Reply to: