F#Async.Parallel是否可以加快计算速度? [英] Does F# Async.Parallel speed up calculations?

查看:119
本文介绍了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天全站免登陆