Python Forum
How can I solve this file handling issue?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I solve this file handling issue?
#12
(Feb-12-2022, 08:51 AM)GiggsB Wrote: bit shifting operation was faster than struct.unpack()

Showing us the results without showing us the code that generated the results is pointless.

Let's do this the right way, using the timeit module

import random
from timeit import Timer
data = [random.randint(0, 255) for i in range(2048)]

t1 = Timer('x = struct.unpack(">" +"I"*512, bytes(data))', setup="import struct; from __main__ import data")
t2 = Timer('''
x = []
for y in range(0, 2048, 4):
    x.append(data[y]<<24 | data[y+1]<<16 | data[y+2]<<8 | data[y+3])
''', setup="from __main__ import data")

print("struct.unpack", min(t1.repeat(number=10000, repeat=7)))
print("manual loop with bitshift", min(t2.repeat(number=10000, repeat=7)))
On my computer, the result is not even close: struct.unpack is about seven times faster than the manual loop. On a Raspberry Pi, your results might be different -- but I would be shocked if the manual loop was faster. The unpack version does most of the work at the speed of C, while the manual loop is doing everything in Python.

In any case, its not really important. Even the slow manual loop version should be fast enough, less than a millisecond. If your code is taking 20 seconds to collect data from the Pi and write it to a file, the bottleneck making it slow is not the part where you convert the list of 8-bit ints to 32-bit ints.
GiggsB and Gribouillis like this post
Reply


Messages In This Thread
RE: How can I solve this file handling issue? - by stevendaprano - Feb-12-2022, 10:07 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  File Handling not working properly TheLummen 8 908 Feb-17-2024, 07:47 PM
Last Post: TheLummen
  file handling Newbee question middlecope 2 844 Jan-18-2023, 03:09 PM
Last Post: middlecope
Star python exception handling handling .... with traceback mg24 3 1,331 Nov-09-2022, 07:29 PM
Last Post: Gribouillis
  Delimiter issue with a CSV file jehoshua 1 1,358 Apr-19-2022, 01:28 AM
Last Post: jehoshua
  File handling issue GiggsB 4 1,506 Mar-31-2022, 09:35 PM
Last Post: GiggsB
  How to solve this file handling issue? GiggsB 3 1,741 Jan-10-2022, 09:36 AM
Last Post: Gribouillis
  File handling knollfinder 3 2,099 Jun-28-2020, 07:39 PM
Last Post: knollfinder
  Writing to File Issue Flash_Stang 3 2,588 Jun-05-2020, 05:14 AM
Last Post: Gribouillis
  file handling sivareddy 1 1,669 Feb-23-2020, 07:28 PM
Last Post: jefsummers
  Simple Read File Issue blackjesus24 4 2,831 Feb-09-2020, 12:07 AM
Last Post: blackjesus24

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020