I have written a script to read from a instrument and writing the data to a CSV-file. The time interval between each sampling can be set by the user. One second sampling rate is quite common. I have used time.sleep and tried to extract the processing time for the script by using timeElapsed = timeEnd - timeBegin. The problem is that this isn't good enough. The time is drifting so every now and then the script jumps over a second. On my computer it happens approx every 2-3 minutes. So my question is how I can increase the accuracy of the timing.
import csv
import datetime
import time
import os.path
no_of_meas = 200
cur_meas = 1
time_interval= 1    #time between each sample given in seconds, 1 second is the lowest recommended value
with open('test.csv', 'a', newline='') as fp:
    while cur_meas <= no_of_meas:
        timeBegin = time.time()
        cur_time = datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S.%f')  
        a = csv.writer(fp, delimiter='\t')
        data = [[cur_time, cur_meas]]
        a.writerows(data)
        fp.flush()   #flush and os.fsync to be sure that data is written to disk
        os.fsync(fp.fileno())
        print(', '.join(map(str, data)))
        cur_meas += 1
        timeEnd = time.time()
        timeElapsed = timeEnd - timeBegin
        time.sleep(time_inter-timeElapsed)
 
     
    