F# Async.Parallel 会加速计算吗? [英] Does F# Async.Parallel speed up calculations?

查看:14
本文介绍了F# Async.Parallel 会加速计算吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Async.Parallel"结构真的有助于在多核系统上加快计算速度吗?.NET TPL任务"是否以某种方式参与其中?

Does the "Async.Parallel" construction really help to make calculations faster on a multi-core system? Are .NET TPL "Tasks" involved here somehow?

open System;

let key = Console.ReadKey(true);
let start = System.DateTime.Now

let pmap f l = seq { for a in l do yield async {return f a} } |> Async.Parallel |> Async.RunSynchronously
let map f l = seq {for a in l do yield f a}

let work f l = 
 match key.KeyChar with 
  | '1' -> pmap f l  
  | '2' -> Seq.toArray (map f l) 
  | _ -> [||]

let result = work (fun x -> (x * x) / 75) (seq { 1 .. 100000*3})
let endtime = DateTime.Now - start 

printfn "%A"endtime;
let pause = Console.ReadKey(true);

我想你们中的一些人会从理论上解释它,但我也会感谢一些现实世界的测试.

I suppose some of you will explain it theoretically, but I would also appreciate some real world tests.

推荐答案

将 F# async 用于纯 CPU 密集型任务,仅当任务执行一些更复杂的操作时才有效.如果您尝试并行化处理非常简单的代码,那么最好使用 PLINQ(和任务并行库),它们针对此类问题进行了更优化.

Using F# async for purely CPU-bound tasks works only if the tasks perform some more complicated operation. If you're trying to parallelize code that does something very simple, then it is better to use PLINQ (and the Task Parallel Library), which are more optimized for these kind of problems.

然而,即便如此,在你所拥有的微不足道的情况下获得加速也很困难.如果你想多尝试一下,你可以试试这个:

However, even then, getting speedup in a trivial case as the one you have is difficult. If you want to experiment with this a bit more, you can try this:

// Turn on timing in F# interactive
#time 
let data = [| 1 .. 5000000*3 |]

// Use standard 'map' function for arrays
let result = Array.map (fun x -> (x * x) / 75) data 
// Use optimized parallel version
let result = Array.Parallel.map (fun x -> (x * x) / 75) data

请注意,使用 Array.map 本身比使用序列表达式然后将结果转换为数组要快得多.如果您想使用比映射更复杂的操作,那么 F# PowerPack 包含 PSeq 模块,其功能类似于 SeqList:

Note that using Array.map itself is a lot faster than using sequence expressions and then converting the result to an array. If you want to use more complex operations than mapping, then F# PowerPack contains PSeq module with functions similar to those in Seq or List:

#r @"FSharp.PowerPack.Parallel.Seq.dll"

data 
|> PSeq.map (fun a -> ...)
|> PSeq.filter (fun a -> ...)
|> PSeq.sort
|> Array.ofSeq

如果你想阅读更多关于这方面的内容,我写了一个关于 parallel 的博客系列最近在 F# 中编程.

If you want to read more about this, I wrote a blog series about parallel programming in F# recently.

这篇关于F# Async.Parallel 会加速计算吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆