单线程&多线程--GPT

发布时间 2023-09-06 03:59:55作者: zhaopw5

Q: 你是个计算机工程师,请用Python分别演示用单线程和多线程计算两个矩阵相乘


GPT-4:

在 Python 中,计算矩阵乘法可以用多种方式实现,包括使用单线程和多线程。以下是两种简单的示例:

单线程

def matrix_multiply(A, B):
    rows_A, cols_A = len(A), len(A[0])
    rows_B, cols_B = len(B), len(B[0])
    
    if cols_A != rows_B:
        return "Cannot multiply the two matrices. They have incompatible dimensions."
    
    # Initialize result matrix filled with zeros
    C = [[0 for row in range(cols_B)] for col in range(rows_A)]
    
    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                C[i][j] += A[i][k] * B[k][j]
    
    return C

A = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

B = [
    [10, 11, 12],
    [13, 14, 15],
    [16, 17, 18]
]

print("Single-threaded result:", matrix_multiply(A, B))

多线程
使用 Python 的 threading 模块进行多线程操作。


import threading

def threaded_matrix_multiply(A, B, C, row_indices):
    cols_A = len(A[0])
    cols_B = len(B[0])
    
    for i in row_indices:
        for j in range(cols_B):
            for k in range(cols_A):
                C[i][j] += A[i][k] * B[k][j]

A = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

B = [
    [10, 11, 12],
    [13, 14, 15],
    [16, 17, 18]
]

rows_A = len(A)
cols_B = len(B[0])

# Initialize result matrix filled with zeros
C = [[0 for row in range(cols_B)] for col in range(rows_A)]

# Create threads
threads = []
split_indices = [[0], [1], [2]]

for indices in split_indices:
    t = threading.Thread(target=threaded_matrix_multiply, args=(A, B, C, indices))
    threads.append(t)
    t.start()

# Wait for all threads to complete
for t in threads:
    t.join()

print("Multi-threaded result:", C)

在这个多线程的例子中,每个线程负责计算结果矩阵的一部分。这样做可以加速计算,尤其是在处理大型矩阵时。

请注意,Python 的 Global Interpreter Lock(GIL)可能会限制多线程代码的效能。对于计算密集型任务,使用多进程或者专门的数值计算库(如 NumPy)通常更加高效。