Closed changxuqing closed 5 months ago
def string_tobitlist(data): ord = ord result = [] append = result.append for ch in data: asciivalue = ord(ch) for i in range(7, -1, -1): append((ascii_value >> i) & 1) return result
def string_to_bitlist2(data): data = [ord(c) for c in data] result = [] for ch in data: i = 7 while i >= 0: if ch & (1 << i) != 0: result.append(1) else: result.append(0) i -= 1 return result
import time
def test_method1(data): start_time = time.time() result = string_to_bitlist(data) end_time = time.time() print("Method 1 Execution Time:", end_time - start_time) return result
def test_method2(data): start_time = time.time() result = string_to_bitlist2(data) end_time = time.time() print("Method 2 Execution Time:", end_time - start_time) return result
import timeit
test_string = "Hello, World!" *1000
number_of_executions = 1000
time1 = timeit.timeit('string_to_bitlist(test_string)', globals=globals(), number=number_of_executions)
print(f"string_to_bitlist: {time1} seconds")
time2 = timeit.timeit('string_to_bitlist2(test_string)', globals=globals(), number=number_of_executions)
print(f"string_to_bitlist2: {time2} seconds")
Hi ,@richtja I compared the speed of the two methods, and the results show that the speed is faster than before when dealing with large data.Here are the results
string_to_bitlist: 8.632775765028782 seconds string_to_bitlist2: 10.137682066997513 seconds
Hi @changxuqing, is there any reason for closing this?
The operations of converting characters to ASCII values and generating a list of bits can be combined into one loop, reducing the number of passes.