pythonsamplingcpu-speed

Different run speeds in python


I want to get a sample from serial port in python. but when I run the code to know the rate of it, python gives me different values! it is usually about 24000 time per second. But sometimes it returns 14000. What is this big difference's reason ? and if I want to sampling 1 million what should I do?

this is the sample code for test run speed:

import time

def g(start=0, stop=5, step=1):
while start < stop:
    yield start
    start += step


t1 = time.time()
t2 = t1 + 1

for item in g(10,1000000,1):
    print(item)
    t1 = time.time()
    if t1 > t2:
        break

Solution

  • Investigate the timeit module, which was designed for applications like this. Benchmarks have to be run under very controlled conditions to be anything like repeatable. timeit runs your code a number of times and gives you the best result. Usually slower performance will be an indication that your computer is running some other task(s) at the same time as the benchmark.