并行编程代码的实现方式取决于你使用的编程语言和库。以下是使用Python的`multiprocessing`库实现并行编程的示例代码:
使用`multiprocessing.Pool`
```python
import multiprocessing
import time
模拟耗时任务
def cpu_bound_task(number):
time.sleep(1)
if __name__ == '__main__':
串行执行
start_time = time.time()
for i in range(5):
cpu_bound_task(i)
end_time = time.time()
print(f"串行执行时间: {end_time - start_time}秒.")
并行执行
start_time_parallel = time.time()
with multiprocessing.Pool(5) as pool:
pool.map(cpu_bound_task, range(5))
end_time_parallel = time.time()
print(f"多进程执行时间: {end_time_parallel - start_time_parallel}秒.")
```
使用`joblib`库
```python
from joblib import Parallel, delayed
import time
模拟耗时任务
def slow_square(x):
time.sleep(1)
return x * x
普通方式
start = time.time()
result1 = [slow_square(i) for i in range(10)]
print(f"普通方式耗时: {time.time() - start}秒")
并行方式
start = time.time()
result2 = Parallel(n_jobs=4)(delayed(slow_square)(i) for i in range(10))
print(f"并行方式耗时: {time.time() - start}秒")
```
使用`concurrent.futures`库
```python
import concurrent.futures
import time
模拟耗时任务
def cpu_bound_task(number):
time.sleep(1)
return number * number
if __name__ == '__main__':
串行执行
start_time = time.time()
for i in range(5):
cpu_bound_task(i)
end_time = time.time()
print(f"串行执行时间: {end_time - start_time}秒.")
并行执行
start_time_parallel = time.time()
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
results = list(executor.map(cpu_bound_task, range(5)))
end_time_parallel = time.time()
print(f"多线程执行时间: {end_time_parallel - start_time_parallel}秒.")
```
使用C的`Parallel.ForEach`
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ParallelTest
{
class ParallelTest
{
private static int TimedMessage(string argMessage, int argInterval)
{
for (int i = 0; i < argInterval; i++)
{
Console.WriteLine(argMessage);
Task.Delay(1000).Wait();
}
return 0;
}
static void Main(string[] args)
{
RetCode = TimedMessage("Five ", 4);
}
}
}
```
使用C++的OpenMP
```cpp
include include include void Hello() { int my_rank = omp_get_thread_num(); int thread_count = omp_get_num_threads(); std::cout << "Hello World from thread " << my_rank << " of " << thread_count << std::endl; } int main(int argc, char* argv[]) { int thread_count = std::strtol(argv, NULL, 10); pragma omp parallel num_threads(thread_count) { Hello(); } return 0; } ``` 总结 使用`multiprocessing`库或`joblib`库可以轻松实现并行编程。 使用`Parallel.ForEach`可以并行执行任务。Python:
C: