Mahdi Jedari
Mahdi Jedari

Reputation: 758

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

Upvotes: 0

Views: 142

Answers (3)

Julien
Julien

Reputation: 1910

I was @15000 at first execution and then arround 28000. In general the result depends mainly of

  • your CPU load
  • cache hit/miss
  • RAM access time

But in your case it is the print which takes most of the execution time. So print access time to stdout is the cause of your variation.

try this :

for item in g(10,100000000,1):
#print(item)
t1 = time.time()
if t1 > t2:
    print(item) #print only the last
    break

Upvotes: 0

turkus
turkus

Reputation: 4903

You will have always some time discrepancies in running code in python, it's because of resources your CPU gives to running your script. You have to make couple of tries and calculate average time of it.

Upvotes: 0

holdenweb
holdenweb

Reputation: 37163

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.

Upvotes: 3

Related Questions