Hướng dẫn how does parallel processing work in python? - xử lý song song hoạt động như thế nào trong python?

Xử lý song song là một chế độ hoạt động trong đó tác vụ được thực hiện đồng thời trong nhiều bộ xử lý trong cùng một máy tính. Nó có nghĩa là để giảm thời gian xử lý tổng thể. Trong hướng dẫn này, bạn sẽ hiểu quy trình để song song hóa bất kỳ logic điển hình nào bằng mô -đun đa xử lý Python.

1. Giới thiệu

Xử lý song song là một chế độ hoạt động trong đó tác vụ được thực hiện đồng thời trong nhiều bộ xử lý trong cùng một máy tính. Nó có nghĩa là để giảm thời gian xử lý tổng thể.

Tuy nhiên, thường có một chút chi phí khi giao tiếp giữa các quá trình thực sự có thể tăng thời gian tổng thể được thực hiện cho các nhiệm vụ nhỏ thay vì giảm nó.

Trong Python, mô -đun

import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]
8 được sử dụng để chạy các quy trình song song độc lập bằng cách sử dụng các quy trình con (thay vì các luồng).

Nó cho phép bạn tận dụng nhiều bộ xử lý trên máy (cả Windows và UNIX), có nghĩa là, các quy trình có thể được chạy ở các vị trí bộ nhớ hoàn toàn riêng biệt. Đến cuối hướng dẫn này, bạn sẽ biết:

  1. Làm thế nào để cấu trúc mã và hiểu cú pháp để cho phép xử lý song song bằng cách sử dụng
    import numpy as np
    from time import time
    
    # Prepare data
    np.random.RandomState(100)
    arr = np.random.randint(0, 10, size=[200000, 5])
    data = arr.tolist()
    data[:5]
    
    8?
  2. Làm thế nào để thực hiện xử lý song song đồng bộ và không đồng bộ?
  3. Làm thế nào để song song hóa một gấu trúc DataFrame?
  4. Giải quyết 3 lần sử dụng khác nhau với giao diện
    # Solution Without Paralleization
    
    def howmany_within_range(row, minimum, maximum):
        """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
        count = 0
        for n in row:
            if minimum <= n <= maximum:
                count = count + 1
        return count
    
    results = []
    for row in data:
        results.append(howmany_within_range(row, minimum=4, maximum=8))
    
    print(results[:10])
    #> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
    
    0.

2. Bạn có thể chạy bao nhiêu quy trình song song tối đa?

Số lượng quy trình tối đa bạn có thể chạy tại một thời điểm bị giới hạn bởi số lượng bộ xử lý trong máy tính của bạn. Nếu bạn không biết có bao nhiêu bộ xử lý có trong máy, chức năng

# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
1 trong
import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]
8 sẽ hiển thị nó.

import multiprocessing as mp
print("Number of processors: ", mp.cpu_count())

3. Thực thi đồng bộ và không đồng bộ là gì?

Trong quá trình xử lý song song, có hai loại thực thi: đồng bộ và không đồng bộ.

Một thực thi đồng bộ là một trong những quá trình được hoàn thành theo cùng một thứ tự mà nó đã được bắt đầu. Điều này đạt được bằng cách khóa chương trình chính cho đến khi các quy trình tương ứng kết thúc.

Mặt khác, không đồng bộ, không liên quan đến việc khóa. Do đó, thứ tự kết quả có thể bị trộn lẫn nhưng thường được thực hiện nhanh hơn.

Có 2 đối tượng chính trong

import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]
8 để thực hiện thực hiện song song một hàm: lớp
# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
4 và lớp
# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
5.

  1. # Solution Without Paralleization
    
    def howmany_within_range(row, minimum, maximum):
        """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
        count = 0
        for n in row:
            if minimum <= n <= maximum:
                count = count + 1
        return count
    
    results = []
    for row in data:
        results.append(howmany_within_range(row, minimum=4, maximum=8))
    
    print(results[:10])
    #> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
    
    4 lớp
    1. Thực thi đồng bộ
      • # Solution Without Paralleization
        
        def howmany_within_range(row, minimum, maximum):
            """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
            count = 0
            for n in row:
                if minimum <= n <= maximum:
                    count = count + 1
            return count
        
        results = []
        for row in data:
            results.append(howmany_within_range(row, minimum=4, maximum=8))
        
        print(results[:10])
        #> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
        
        7 và
        # Solution Without Paralleization
        
        def howmany_within_range(row, minimum, maximum):
            """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
            count = 0
            for n in row:
                if minimum <= n <= maximum:
                    count = count + 1
            return count
        
        results = []
        for row in data:
            results.append(howmany_within_range(row, minimum=4, maximum=8))
        
        print(results[:10])
        #> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
        
        8
      • # Solution Without Paralleization
        
        def howmany_within_range(row, minimum, maximum):
            """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
            count = 0
            for n in row:
                if minimum <= n <= maximum:
                    count = count + 1
            return count
        
        results = []
        for row in data:
            results.append(howmany_within_range(row, minimum=4, maximum=8))
        
        print(results[:10])
        #> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
        
        9
    2. Thực thi không đồng bộ
      • # Parallelizing using Pool.apply()
        
        import multiprocessing as mp
        
        # Step 1: Init multiprocessing.Pool()
        pool = mp.Pool(mp.cpu_count())
        
        # Step 2: `pool.apply` the `howmany_within_range()`
        results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]
        
        # Step 3: Don't forget to close
        pool.close()    
        
        print(results[:10])
        #> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
        
        0 và
        # Parallelizing using Pool.apply()
        
        import multiprocessing as mp
        
        # Step 1: Init multiprocessing.Pool()
        pool = mp.Pool(mp.cpu_count())
        
        # Step 2: `pool.apply` the `howmany_within_range()`
        results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]
        
        # Step 3: Don't forget to close
        pool.close()    
        
        print(results[:10])
        #> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
        
        1
      • # Parallelizing using Pool.apply()
        
        import multiprocessing as mp
        
        # Step 1: Init multiprocessing.Pool()
        pool = mp.Pool(mp.cpu_count())
        
        # Step 2: `pool.apply` the `howmany_within_range()`
        results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]
        
        # Step 3: Don't forget to close
        pool.close()    
        
        print(results[:10])
        #> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
        
        2)
  2. # Solution Without Paralleization
    
    def howmany_within_range(row, minimum, maximum):
        """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
        count = 0
        for n in row:
            if minimum <= n <= maximum:
                count = count + 1
        return count
    
    results = []
    for row in data:
        results.append(howmany_within_range(row, minimum=4, maximum=8))
    
    print(results[:10])
    #> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
    
    5 lớp

Hãy cùng đưa ra một vấn đề điển hình và thực hiện song song bằng cách sử dụng các kỹ thuật trên.

Trong hướng dẫn này, chúng tôi gắn bó với lớp

# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
4, bởi vì việc sử dụng và phục vụ các ứng dụng thực tế phổ biến nhất là thuận tiện nhất.

4. Tuyên bố vấn đề: Đếm số lượng số tồn tại giữa một phạm vi nhất định trong mỗi hàng

Vấn đề đầu tiên là: Cho ma trận 2D (hoặc danh sách danh sách), hãy đếm số lượng có mặt giữa một phạm vi nhất định trong mỗi hàng. Chúng tôi sẽ làm việc trong danh sách được chuẩn bị dưới đây.

import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]

Giải pháp mà không song song

Hãy cùng xem mất bao lâu để tính toán nó mà không cần song song.

Đối với điều này, chúng tôi lặp lại hàm

# Parallelizing using Pool.apply()

import multiprocessing as mp

# Step 1: Init multiprocessing.Pool()
pool = mp.Pool(mp.cpu_count())

# Step 2: `pool.apply` the `howmany_within_range()`
results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]

# Step 3: Don't forget to close
pool.close()    

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
5 (được viết bên dưới) để kiểm tra xem có bao nhiêu số nằm trong phạm vi và trả về số lượng.

Nhận khóa học Python hoàn thành miễn phí

Đối mặt với tình huống tương tự như mọi người khác?

Xây dựng sự nghiệp khoa học dữ liệu của bạn với trình độ được công nhận trên toàn cầu, được công nghiệp phê duyệt. Có được suy nghĩ, sự tự tin và các kỹ năng làm cho nhà khoa học dữ liệu trở nên có giá trị.

Hướng dẫn how does parallel processing work in python? - xử lý song song hoạt động như thế nào trong python?

Nhận khóa học Python hoàn thành miễn phí

Xây dựng sự nghiệp khoa học dữ liệu của bạn với trình độ được công nhận trên toàn cầu, được công nghiệp phê duyệt. Có được suy nghĩ, sự tự tin và các kỹ năng làm cho nhà khoa học dữ liệu trở nên có giá trị.

# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]

& nbsp; & nbsp;

5. Làm thế nào để song song hóa bất kỳ chức năng?

Cách chung để song song hóa bất kỳ hoạt động nào là thực hiện một chức năng cụ thể sẽ được chạy nhiều lần và làm cho nó chạy tương đồng trong các bộ xử lý khác nhau.

Để thực hiện điều này, bạn khởi tạo một

# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
4 với n số lượng bộ xử lý và truyền chức năng bạn muốn song song hóa với một trong các phương thức tương đương
# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
4S.

# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0 cung cấp các phương thức
# Parallelizing using Pool.apply()

import multiprocessing as mp

# Step 1: Init multiprocessing.Pool()
pool = mp.Pool(mp.cpu_count())

# Step 2: `pool.apply` the `howmany_within_range()`
results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]

# Step 3: Don't forget to close
pool.close()    

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
9,
# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0 và
# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
1 để thực hiện bất kỳ chức năng nào chạy song song.

Nice!

Vì vậy, những gì khác biệt giữa

# Parallelizing using Pool.apply()

import multiprocessing as mp

# Step 1: Init multiprocessing.Pool()
pool = mp.Pool(mp.cpu_count())

# Step 2: `pool.apply` the `howmany_within_range()`
results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]

# Step 3: Don't forget to close
pool.close()    

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
9 và
# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0?

Cả

# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
4 và
# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
5 đều lấy hàm để được song song làm đối số chính.

Nhưng sự khác biệt là,

# Parallelizing using Pool.apply()

import multiprocessing as mp

# Step 1: Init multiprocessing.Pool()
pool = mp.Pool(mp.cpu_count())

# Step 2: `pool.apply` the `howmany_within_range()`
results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]

# Step 3: Don't forget to close
pool.close()    

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
9 lấy một đối số
# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
7 chấp nhận các tham số được truyền cho ‘chức năng tương tự như một đối số, trong khi đó,
# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
5 chỉ có thể lấy một điều có thể xảy ra như một đối số.

Vì vậy,

# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0 thực sự phù hợp hơn cho các hoạt động đơn giản hơn nhưng công việc nhanh hơn.

Chúng ta sẽ nhận được

# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
1 khi chúng ta thấy cách song song hóa chức năng
# Parallelizing using Pool.apply()

import multiprocessing as mp

# Step 1: Init multiprocessing.Pool()
pool = mp.Pool(mp.cpu_count())

# Step 2: `pool.apply` the `howmany_within_range()`
results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]

# Step 3: Don't forget to close
pool.close()    

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
5 với
# Parallelizing using Pool.apply()

import multiprocessing as mp

# Step 1: Init multiprocessing.Pool()
pool = mp.Pool(mp.cpu_count())

# Step 2: `pool.apply` the `howmany_within_range()`
results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]

# Step 3: Don't forget to close
pool.close()    

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
9 và
# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0.

5.1. Song song bằng cách sử dụng pool.apply ()

Hãy để song song với chức năng

# Parallelizing using Pool.apply()

import multiprocessing as mp

# Step 1: Init multiprocessing.Pool()
pool = mp.Pool(mp.cpu_count())

# Step 2: `pool.apply` the `howmany_within_range()`
results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]

# Step 3: Don't forget to close
pool.close()    

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
5 bằng cách sử dụng
# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0.

# Parallelizing using Pool.apply()

import multiprocessing as mp

# Step 1: Init multiprocessing.Pool()
pool = mp.Pool(mp.cpu_count())

# Step 2: `pool.apply` the `howmany_within_range()`
results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]

# Step 3: Don't forget to close
pool.close()    

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]

5.2. Song song bằng cách sử dụng pool.map ()

# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
7 chỉ chấp nhận một điều có thể là đối số.

Vì vậy, với tư cách là một cách giải quyết, tôi sửa đổi hàm

# Parallelizing with Pool.starmap()
import multiprocessing as mp

pool = mp.Pool(mp.cpu_count())

results = pool.starmap(howmany_within_range, [(row, 4, 8) for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
7 bằng cách đặt mặc định thành các tham số
# Parallelizing with Pool.starmap()
import multiprocessing as mp

pool = mp.Pool(mp.cpu_count())

results = pool.starmap(howmany_within_range, [(row, 4, 8) for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
8 và
# Parallelizing with Pool.starmap()
import multiprocessing as mp

pool = mp.Pool(mp.cpu_count())

results = pool.starmap(howmany_within_range, [(row, 4, 8) for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
9 để tạo hàm
# Parallel processing with Pool.apply_async()

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

# Step 1: Redefine, to accept `i`, the iteration number
def howmany_within_range2(i, row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return (i, count)


# Step 2: Define callback function to collect the output in `results`
def collect_result(result):
    global results
    results.append(result)


# Step 3: Use loop to parallelize
for i, row in enumerate(data):
    pool.apply_async(howmany_within_range2, args=(i, row, 4, 8), callback=collect_result)

# Step 4: Close Pool and let all the processes complete    
pool.close()
pool.join()  # postpones the execution of next line of code until all processes in the queue are done.

# Step 5: Sort results [OPTIONAL]
results.sort(key=lambda x: x[0])
results_final = [r for i, r in results]

print(results_final[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0 mới để nó chỉ kích thích một danh sách các hàng có thể lặp lại làm đầu vào.

Tôi biết đây không phải là một Usecase tốt đẹp là

# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0, nhưng nó cho thấy rõ nó khác với
# Parallelizing using Pool.apply()

import multiprocessing as mp

# Step 1: Init multiprocessing.Pool()
pool = mp.Pool(mp.cpu_count())

# Step 2: `pool.apply` the `howmany_within_range()`
results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]

# Step 3: Don't forget to close
pool.close()    

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
9 như thế nào.

# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]

5.3. Song song bằng cách sử dụng pool.starmap ()

Trong ví dụ trước, chúng ta phải xác định lại hàm

# Parallelizing with Pool.starmap()
import multiprocessing as mp

pool = mp.Pool(mp.cpu_count())

results = pool.starmap(howmany_within_range, [(row, 4, 8) for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
7 để tạo một vài tham số để lấy các giá trị mặc định.

Sử dụng

# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
1, bạn có thể tránh làm điều này.

Bạn hỏi như thế nào?

Giống như

# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
7,
# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
8 cũng chỉ chấp nhận một điều có thể xảy ra như một đối số, nhưng trong
# Parallelizing using Pool.map()
import multiprocessing as mp

# Redefine, with only 1 mandatory argument.
def howmany_within_range_rowonly(row, minimum=4, maximum=8):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

pool = mp.Pool(mp.cpu_count())

results = pool.map(howmany_within_range_rowonly, [row for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
1, mỗi yếu tố trong đó có thể sử dụng được cũng là một điều có thể.

Bạn có thể cung cấp các đối số cho ‘chức năng với song song với cùng một thứ tự trong phần tử IT có thể điều chỉnh bên trong này, sẽ lần lượt được giải nén trong quá trình thực thi.

Vì vậy, một cách hiệu quả,

# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
8 giống như một phiên bản của
# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
7 chấp nhận các đối số.

# Parallelizing with Pool.starmap()
import multiprocessing as mp

pool = mp.Pool(mp.cpu_count())

results = pool.starmap(howmany_within_range, [(row, 4, 8) for row in data])

pool.close()

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]

6. Xử lý song song không đồng bộ

Các tương đương không đồng bộ

# Parallel processing with Pool.apply_async() without callback function

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

# call apply_async() without callback
result_objects = [pool.apply_async(howmany_within_range2, args=(i, row, 4, 8)) for i, row in enumerate(data)]

# result_objects is a list of pool.ApplyResult objects
results = [r.get()[1] for r in result_objects]

pool.close()
pool.join()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0,
# Parallel processing with Pool.apply_async() without callback function

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

# call apply_async() without callback
result_objects = [pool.apply_async(howmany_within_range2, args=(i, row, 4, 8)) for i, row in enumerate(data)]

# result_objects is a list of pool.ApplyResult objects
results = [r.get()[1] for r in result_objects]

pool.close()
pool.join()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
1 và
# Parallel processing with Pool.apply_async() without callback function

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

# call apply_async() without callback
result_objects = [pool.apply_async(howmany_within_range2, args=(i, row, 4, 8)) for i, row in enumerate(data)]

# result_objects is a list of pool.ApplyResult objects
results = [r.get()[1] for r in result_objects]

pool.close()
pool.join()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
2 cho phép bạn thực hiện các quy trình song song không đồng bộ, đó là quá trình tiếp theo có thể bắt đầu ngay khi trước đó không quan tâm đến thứ tự bắt đầu.

Kết quả là, không có gì đảm bảo rằng kết quả sẽ theo cùng thứ tự với đầu vào.

6.1 song song với pool.apply_async ()

# Parallel processing with Pool.apply_async() without callback function

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

# call apply_async() without callback
result_objects = [pool.apply_async(howmany_within_range2, args=(i, row, 4, 8)) for i, row in enumerate(data)]

# result_objects is a list of pool.ApplyResult objects
results = [r.get()[1] for r in result_objects]

pool.close()
pool.join()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0 rất giống với
# Parallelizing using Pool.apply()

import multiprocessing as mp

# Step 1: Init multiprocessing.Pool()
pool = mp.Pool(mp.cpu_count())

# Step 2: `pool.apply` the `howmany_within_range()`
results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]

# Step 3: Don't forget to close
pool.close()    

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
9 ngoại trừ việc bạn cần cung cấp chức năng gọi lại cho biết các kết quả được tính toán nên được lưu trữ như thế nào.

Tuy nhiên, một cảnh báo với

# Parallel processing with Pool.apply_async() without callback function

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

# call apply_async() without callback
result_objects = [pool.apply_async(howmany_within_range2, args=(i, row, 4, 8)) for i, row in enumerate(data)]

# result_objects is a list of pool.ApplyResult objects
results = [r.get()[1] for r in result_objects]

pool.close()
pool.join()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0 là, thứ tự các số trong kết quả bị xáo trộn cho thấy các quy trình không hoàn thành theo thứ tự nó được bắt đầu.

Một cách giải quyết cho điều này là, chúng tôi xác định lại một

# Parallel processing with Pool.apply_async() without callback function

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

# call apply_async() without callback
result_objects = [pool.apply_async(howmany_within_range2, args=(i, row, 4, 8)) for i, row in enumerate(data)]

# result_objects is a list of pool.ApplyResult objects
results = [r.get()[1] for r in result_objects]

pool.close()
pool.join()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
6 mới để chấp nhận và trả về số lặp (
# Parallel processing with Pool.apply_async() without callback function

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

# call apply_async() without callback
result_objects = [pool.apply_async(howmany_within_range2, args=(i, row, 4, 8)) for i, row in enumerate(data)]

# result_objects is a list of pool.ApplyResult objects
results = [r.get()[1] for r in result_objects]

pool.close()
pool.join()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
7) và sau đó sắp xếp các kết quả cuối cùng.

# Parallel processing with Pool.apply_async()

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

# Step 1: Redefine, to accept `i`, the iteration number
def howmany_within_range2(i, row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return (i, count)


# Step 2: Define callback function to collect the output in `results`
def collect_result(result):
    global results
    results.append(result)


# Step 3: Use loop to parallelize
for i, row in enumerate(data):
    pool.apply_async(howmany_within_range2, args=(i, row, 4, 8), callback=collect_result)

# Step 4: Close Pool and let all the processes complete    
pool.close()
pool.join()  # postpones the execution of next line of code until all processes in the queue are done.

# Step 5: Sort results [OPTIONAL]
results.sort(key=lambda x: x[0])
results_final = [r for i, r in results]

print(results_final[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]

Có thể sử dụng

# Parallel processing with Pool.apply_async() without callback function

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

# call apply_async() without callback
result_objects = [pool.apply_async(howmany_within_range2, args=(i, row, 4, 8)) for i, row in enumerate(data)]

# result_objects is a list of pool.ApplyResult objects
results = [r.get()[1] for r in result_objects]

pool.close()
pool.join()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0 mà không cung cấp chức năng
# Parallel processing with Pool.apply_async() without callback function

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

# call apply_async() without callback
result_objects = [pool.apply_async(howmany_within_range2, args=(i, row, 4, 8)) for i, row in enumerate(data)]

# result_objects is a list of pool.ApplyResult objects
results = [r.get()[1] for r in result_objects]

pool.close()
pool.join()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
9.

Chỉ có vậy, nếu bạn không cung cấp một cuộc gọi lại, thì bạn sẽ nhận được một danh sách các đối tượng

# Parallelizing with Pool.starmap_async()

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

results = pool.starmap_async(howmany_within_range2, [(i, row, 4, 8) for i, row in enumerate(data)]).get()

# With map, use `howmany_within_range_rowonly` instead
# results = pool.map_async(howmany_within_range_rowonly, [row for row in data]).get()

pool.close()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0 chứa các giá trị đầu ra được tính toán từ mỗi quy trình.

Từ đó, bạn cần sử dụng phương thức

# Parallelizing with Pool.starmap_async()

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

results = pool.starmap_async(howmany_within_range2, [(i, row, 4, 8) for i, row in enumerate(data)]).get()

# With map, use `howmany_within_range_rowonly` instead
# results = pool.map_async(howmany_within_range_rowonly, [row for row in data]).get()

pool.close()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
1 để lấy kết quả cuối cùng mong muốn.

# Parallel processing with Pool.apply_async() without callback function

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

# call apply_async() without callback
result_objects = [pool.apply_async(howmany_within_range2, args=(i, row, 4, 8)) for i, row in enumerate(data)]

# result_objects is a list of pool.ApplyResult objects
results = [r.get()[1] for r in result_objects]

pool.close()
pool.join()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]

6.2 song song với pool.starmap_async ()

Bạn đã thấy cách

# Parallel processing with Pool.apply_async() without callback function

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

# call apply_async() without callback
result_objects = [pool.apply_async(howmany_within_range2, args=(i, row, 4, 8)) for i, row in enumerate(data)]

# result_objects is a list of pool.ApplyResult objects
results = [r.get()[1] for r in result_objects]

pool.close()
pool.join()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
0 hoạt động.

Bạn có thể tưởng tượng và viết lên một phiên bản tương đương cho

# Parallelizing with Pool.starmap_async()

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

results = pool.starmap_async(howmany_within_range2, [(i, row, 4, 8) for i, row in enumerate(data)]).get()

# With map, use `howmany_within_range_rowonly` instead
# results = pool.map_async(howmany_within_range_rowonly, [row for row in data]).get()

pool.close()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
3 và
# Parallelizing with Pool.starmap_async()

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

results = pool.starmap_async(howmany_within_range2, [(i, row, 4, 8) for i, row in enumerate(data)]).get()

# With map, use `howmany_within_range_rowonly` instead
# results = pool.map_async(howmany_within_range_rowonly, [row for row in data]).get()

pool.close()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
4 không?

Việc thực hiện ở dưới dù sao.

# Parallelizing with Pool.starmap_async()

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

results = pool.starmap_async(howmany_within_range2, [(i, row, 4, 8) for i, row in enumerate(data)]).get()

# With map, use `howmany_within_range_rowonly` instead
# results = pool.map_async(howmany_within_range_rowonly, [row for row in data]).get()

pool.close()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]

7. Làm thế nào để song song hóa một bản dữ liệu gấu trúc?

Cho đến nay, bạn đã thấy cách song song hóa một chức năng bằng cách làm cho nó hoạt động trong danh sách.

Nhưng khi làm việc trong phân tích dữ liệu hoặc các dự án học máy, bạn có thể muốn song song hóa các khung dữ liệu gấu trúc, là các đối tượng được sử dụng phổ biến nhất (bên cạnh các mảng Numpy) để lưu trữ dữ liệu bảng.

Khi nói đến song song với

# Parallelizing with Pool.starmap_async()

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

results = pool.starmap_async(howmany_within_range2, [(i, row, 4, 8) for i, row in enumerate(data)]).get()

# With map, use `howmany_within_range_rowonly` instead
# results = pool.map_async(howmany_within_range_rowonly, [row for row in data]).get()

pool.close()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
5, bạn có thể thực hiện các chức năng song song để lấy làm tham số đầu vào:

  • Một hàng của DataFrame
  • Một cột của DataFrame
  • toàn bộ khung dữ liệu

2 đầu tiên có thể được thực hiện bằng cách sử dụng mô -đun

import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]
8.

Nhưng đối với cái cuối cùng, đó là song song trên toàn bộ khung dữ liệu, chúng tôi sẽ sử dụng gói

# Parallelizing with Pool.starmap_async()

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

results = pool.starmap_async(howmany_within_range2, [(i, row, 4, 8) for i, row in enumerate(data)]).get()

# With map, use `howmany_within_range_rowonly` instead
# results = pool.map_async(howmany_within_range_rowonly, [row for row in data]).get()

pool.close()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
7 sử dụng
# Parallelizing with Pool.starmap_async()

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

results = pool.starmap_async(howmany_within_range2, [(i, row, 4, 8) for i, row in enumerate(data)]).get()

# With map, use `howmany_within_range_rowonly` instead
# results = pool.map_async(howmany_within_range_rowonly, [row for row in data]).get()

pool.close()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
8 để tuần tự hóa trong nội bộ.

Đầu tiên, hãy tạo một DataFrame mẫu và xem cách thực hiện các giao dịch thông minh và khôn ngoan về cột.

Một cái gì đó như sử dụng

# Parallelizing with Pool.starmap_async()

import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())

results = []

results = pool.starmap_async(howmany_within_range2, [(i, row, 4, 8) for i, row in enumerate(data)]).get()

# With map, use `howmany_within_range_rowonly` instead
# results = pool.map_async(howmany_within_range_rowonly, [row for row in data]).get()

pool.close()
print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
9 trên hàm do người dùng xác định nhưng song song.

import numpy as np
import pandas as pd
import multiprocessing as mp

df = pd.DataFrame(np.random.randint(3, 10, size=[5, 2]))
print(df.head())
#>    0  1
#> 0  8  5
#> 1  5  3
#> 2  3  4
#> 3  4  4
#> 4  7  9

Chúng tôi có một khung dữ liệu. Hãy để áp dụng chức năng

import numpy as np
import pandas as pd
import multiprocessing as mp

df = pd.DataFrame(np.random.randint(3, 10, size=[5, 2]))
print(df.head())
#>    0  1
#> 0  8  5
#> 1  5  3
#> 2  3  4
#> 3  4  4
#> 4  7  9
0 trên mỗi hàng, nhưng chạy 4 quy trình cùng một lúc.

Để làm điều này, chúng tôi khai thác

import numpy as np
import pandas as pd
import multiprocessing as mp

df = pd.DataFrame(np.random.randint(3, 10, size=[5, 2]))
print(df.head())
#>    0  1
#> 0  8  5
#> 1  5  3
#> 2  3  4
#> 3  4  4
#> 4  7  9
1.

Bằng cách đặt

import numpy as np
import pandas as pd
import multiprocessing as mp

df = pd.DataFrame(np.random.randint(3, 10, size=[5, 2]))
print(df.head())
#>    0  1
#> 0  8  5
#> 1  5  3
#> 2  3  4
#> 3  4  4
#> 4  7  9
2, bạn đang chuyển từng hàng của DataFrame dưới dạng một bộ đơn giản cho hàm
import numpy as np
import pandas as pd
import multiprocessing as mp

df = pd.DataFrame(np.random.randint(3, 10, size=[5, 2]))
print(df.head())
#>    0  1
#> 0  8  5
#> 1  5  3
#> 2  3  4
#> 3  4  4
#> 4  7  9
0.

import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]
0

Đó là một ví dụ về song song hàng ngày.

Hãy để Lừa cũng làm một song song hóa cột.

Đối với điều này, tôi sử dụng

import numpy as np
import pandas as pd
import multiprocessing as mp

df = pd.DataFrame(np.random.randint(3, 10, size=[5, 2]))
print(df.head())
#>    0  1
#> 0  8  5
#> 1  5  3
#> 2  3  4
#> 3  4  4
#> 4  7  9
4 để chuyển toàn bộ cột làm chuỗi cho hàm
import numpy as np
import pandas as pd
import multiprocessing as mp

df = pd.DataFrame(np.random.randint(3, 10, size=[5, 2]))
print(df.head())
#>    0  1
#> 0  8  5
#> 1  5  3
#> 2  3  4
#> 3  4  4
#> 4  7  9
5.

import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]
1

Bây giờ đến phần thứ ba - song song hóa một hàm chấp nhận dữ liệu gấu trúc, mảng numpy, v.v ... Pathos theo kiểu

import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]
8 của: POOL> MAP> Đóng> Tham gia> Xóa.

Kiểm tra các tài liệu Pathos để biết thêm thông tin.

import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]
2

Cảm ơn NotSoprocoder vì sự đóng góp này dựa trên Pathos.

Nếu bạn đã quen thuộc với các khung dữ liệu gấu trúc nhưng muốn thực hành và làm chủ nó, hãy xem các bài tập gấu trúc này.

8. Bài tập

Bài 1: Sử dụng

# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
9 để có được hàng thông minh các mục thông thường trong
import numpy as np
import pandas as pd
import multiprocessing as mp

df = pd.DataFrame(np.random.randint(3, 10, size=[5, 2]))
print(df.head())
#>    0  1
#> 0  8  5
#> 1  5  3
#> 2  3  4
#> 3  4  4
#> 4  7  9
8 và
import numpy as np
import pandas as pd
import multiprocessing as mp

df = pd.DataFrame(np.random.randint(3, 10, size=[5, 2]))
print(df.head())
#>    0  1
#> 0  8  5
#> 1  5  3
#> 2  3  4
#> 3  4  4
#> 4  7  9
9.
Use
# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
9 to get the row wise common items in
import numpy as np
import pandas as pd
import multiprocessing as mp

df = pd.DataFrame(np.random.randint(3, 10, size=[5, 2]))
print(df.head())
#>    0  1
#> 0  8  5
#> 1  5  3
#> 2  3  4
#> 3  4  4
#> 4  7  9
8 and
import numpy as np
import pandas as pd
import multiprocessing as mp

df = pd.DataFrame(np.random.randint(3, 10, size=[5, 2]))
print(df.head())
#>    0  1
#> 0  8  5
#> 1  5  3
#> 2  3  4
#> 3  4  4
#> 4  7  9
9.

import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]
3

Hiển thị giải pháp

import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]
4

Bài 2: Sử dụng

# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
7 để chạy song song các tập lệnh Python sau. Tên tập lệnh: ‘script1.py,‘ script2.py, ‘script3.py, hiển thị giải pháp Use
# Solution Without Paralleization

def howmany_within_range(row, minimum, maximum):
    """Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count = count + 1
    return count

results = []
for row in data:
    results.append(howmany_within_range(row, minimum=4, maximum=8))

print(results[:10])
#> [3, 1, 4, 4, 4, 2, 1, 1, 3, 3]
7 to run the following python scripts in parallel. Script names: ‘script1.py’, ‘script2.py’, ‘script3.py’ Show Solution

import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]
5

Bài 3: Bình thường hóa từng hàng của mảng 2D (danh sách) thành thay đổi giữa 0 đến 1. Normalize each row of 2d array (list) to vary between 0 and 1.

import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]
6

Hiển thị giải pháp

import numpy as np
from time import time

# Prepare data
np.random.RandomState(100)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()
data[:5]
7

9. Kết luận

Hy vọng bạn đã có thể giải quyết các bài tập trên, xin chúc mừng nếu bạn đã làm! Trong bài đăng này, chúng tôi đã thấy quy trình tổng thể và nhiều cách khác nhau để thực hiện xử lý song song bằng mô -đun đa xử lý. Quy trình được mô tả ở trên là khá giống nhau ngay cả khi bạn làm việc trên các máy lớn hơn với nhiều số bộ xử lý hơn, nơi bạn có thể gặt hái những lợi ích tốc độ thực của xử lý song song. Happy Coding và tôi sẽ gặp bạn trong phần tiếp theo!

Bài viết đề xuất

Hướng dẫn của Dask - Cách xử lý dữ liệu lớn trong Hướng dẫn Python Python JSON Python Regex Hướng dẫn đăng nhập Python Hướng dẫn Bộ sưu tập Python Hướng dẫn về Mô -đun yêu cầu Python

Xử lý song song trong Python là gì?

Đa xử lý Python: Song song dựa trên quá trình trong Python Mô-đun đa xử lý cho phép bạn tạo nhiều quy trình, mỗi trong số chúng với trình thông dịch Python riêng. Vì lý do này, đa xử lý Python hoàn thành song song dựa trên quá trình.The multiprocessing module allows you to create multiple processes, each of them with its own Python interpreter. For this reason, Python multiprocessing accomplishes process-based parallelism.

Làm thế nào để xử lý song song hoạt động?

Xử lý song song liên quan đến việc thực hiện một nhiệm vụ lớn, chia nó thành một số nhiệm vụ nhỏ hơn, và sau đó làm việc trên từng nhiệm vụ nhỏ hơn đó.Mục tiêu của cách tiếp cận phân chia và chinh phục này là hoàn thành nhiệm vụ lớn hơn trong thời gian ngắn hơn so với việc thực hiện nó trong một khối lớn.taking a large task, dividing it into several smaller tasks, and then working on each of those smaller tasks simultaneously. The goal of this divide-and-conquer approach is to complete the larger task in less time than it would have taken to do it in one large chunk.

Có thể lập trình song song trong Python?

Có một số cách phổ biến để song song hóa mã Python.Bạn có thể khởi chạy một số trường hợp ứng dụng hoặc tập lệnh để thực hiện song song.Cách tiếp cận này là tuyệt vời khi bạn không cần trao đổi dữ liệu giữa các công việc song song.. You can launch several application instances or a script to perform jobs in parallel. This approach is great when you don't need to exchange data between parallel jobs.

Làm thế nào để xếp hàng đa xử lý Python hoạt động?

Đa xử lý.Hàng đợi cung cấp hàng đợi FIFO đầu tiên, đầu tiên, có nghĩa là các mục được lấy từ hàng đợi theo thứ tự chúng được thêm vào.Các mục đầu tiên được thêm vào hàng đợi sẽ là các mục đầu tiên được truy xuất.provides a first-in, first-out FIFO queue, which means that the items are retrieved from the queue in the order they were added. The first items added to the queue will be the first items retrieved.