pythonmathnewtons-method

How can I accurately measure small time differences in Python?


I'm working on a project for which I'm analyzing how quickly Newton's method can calculate a zero of a function from different starting points. I've written the program below and everything seems to be working except the calculation of the time difference. Because the method is quite fast, the time difference is also quite small and I think that because of that, Python interprets it as zero, so the output is nearly always zero. Is there any way to calculate this more accurately?

P.S.: I'm quite new to coding, so I'm sorry if my code is a bit of a mess, but I hope you can help me.

My code:

import math
import time

#enter function
def f(x):
    return x**2 - 4

#enter derivative
def fderiv(x):
    return 2*x

#Newton's method
def Newton(x):
    return (x - f(x)/fderiv(x))

#enter zero
zero = 2

#change starting point
for n in range(-100,100):
    start = zero + n/100
    #apply Newton on starting point
    current = start
    starttime = time.time()
    difference = abs(current - zero)
    try:
        while difference > 0.00001:
            current = Newton(current)
            difference = abs(current - zero)
        elapsed_time = time.time()-starttime
        print(str(start), ": elapsed time is: %.10f" % (elapsed_time))
    except:
        print(str(start), ": Error")

I've tried using some different methods, like datetime.fromtimestamp(), time.time_ns() or process_time(), but none of them seem to be working. The output is still mostly zeroes. Any ideas on how to fix it?


Solution

  • For high-resolution timing, use time.perf_counter().