Re: More accurate time feedback
On Wed, Oct 24, 2001 at 06:29:39PM -0500, Ian Patrick Thomas wrote:
| Is there a way to get a more accurate time value, preferably to a
| nanosecond, using the system clock? I need to write a program that needs to
| output the time it takes various sorting algprithms to sort various numbers
| of integers. For smaller numbers of integers on algorithms like quicksort,
| and mergesort, I am getting 0 for the runtime. I need a function that I can
| call before the sort begins and after it ends that would return a time
| value, preferably to the nanosecond. Is there a library out there that can
| do this or is the answer right on my machine and I just haven't found it
| yet?
One way is to use a dataset that is big enough to measure. If you
encapsulate the algorithm in an application (that is, something that
can be run as a process) then the 'time' program can do all the
measuring for you.
Otherwise you need to determine what sort of time measuring stuff is
available for the development environment you are using. For example,
if you are using python :
#!/usr/bin/env python
import random
import time
def qsort( data ) :
for i in xrange( random.randint( 5 , 10 ) ) :
time.sleep( 1 ) # take up time as if we did something useful
def mergesort( data ) :
for i in xrange( random.randint( 5 , 10 ) ) :
time.sleep( 1 ) # take up time as if we did something useful
start = time.time()
qsort( [ "some data" ] )
end = time.time()
print "qsort took %d units of time" % (end - start)
start = time.time()
mergesort( [ "some data" ] )
end = time.time()
print "mergesort took %d units of time" % (end - start)
$ time ./test.py # demonstrating both at once
qsort took 6 units of time
mergesort took 5 units of time
real 0m17.047s
user 0m0.040s
sys 0m0.000s
$
From the python docs :
time()
Return the time as a floating point number expressed in
seconds since the epoch, in UTC. Note that even though the
time is always returned as a floating point number, not all
systems provide time with a better precision than 1 second.
HTH,
-D
Reply to: