2

I have a code written in Python that takes about 9% of the CPU when ran. I want it to use more so it can run faster. To solve this problem, I tried multiprocessing, however, before writing a code for it, I ran the same program in two different terminal which created two different Python processes. However, instead of each taking 9% of the CPU for a total of about 18% of CPU, each take about 5% for a total of 10% CPU. How can I change that and have each process take 9% of CPU or have just one program take >20% of CPU?

Thank you!

    import spidev, time, os

# opens SPI bus
spi = spidev.SpiDev()
spi.open(0, 0)

#spi1 = spidev.SpiDev()
#spi1.open(0, 1)

ch0 = 0
#ch1 = 1

now = time.time() * 1000
data = open("test_plot.dat", "w")
#data1 = open("test_plot_1.dat", "w")

def getReading(channel):
    # pull raw data from chip
    rawData = spi.xfer([1, (8 + channel) << 4, 0])
    # process raw data to something we understand
    processedData = ((rawData[1]&3) << 8) + rawData[2]
    return processedData
"""
def getReading1(channel):
    # pull raw data from chip
    rawData = spi1.xfer([1, (8 + channel) << 4, 0])
    # process raw data to something we understand
    processedData = ((rawData[1]&3) << 8) + rawData[2]
    return processedData
"""
while True:
    if (((time.time() * 1000) - now) < 10001):
        data.write("%d\n" % getReading(ch0))
        #data1.write("%d\n" % getReading1(ch1))
    else:
        break

# http://www.takaitra.com/posts/492

1 Answers1

3

You have two bottlenecks here that are going to slow you down. First, there's the SPI, which was mentioned in a comment. That takes a few clock cycles in each direction and will limit you some. The second is writing to the SD card. I expect that the second is more important for your speed. Disk writes are generally much slower than computations, and the SD card is even slower than disk.

If you just want to use the whole number of CPU cycles, try taking those out and see what happens. Of course that means you won't be accomplishing your task, so then you'll need to put them back in some other way. A possible option would be to buffer your write-to-disk operations and have them trickle out in their own thread while the rest of the code runs. This may or may not work - For example, you might over-run the buffer and crash. You'll have to do some design and experimentation.

Brick
  • 1,375
  • 2
  • 14
  • 20