我在下面使用这个函数,我想利用并行性(他们所谓的好处),但是,当我尝试实现一个简单的 P 并行 LINQ 技术结果非常消极,我不知道为什么,但总执行时间增加了10左右。
<DebuggerStepThrough>
Public Shared Function PermuteCharacters(ByVal charSet As Char(),
ByVal length As Integer,
ByVal allowRepetition As Boolean) As IEnumerable(Of String)
If (charSet.Count <> charSet.Distinct.Count) Then
Throw New ArgumentException("Char-set contains duplicated characters.", "charSet")
Return Nothing
End If
If (length = 1) Then
Return charSet.Select(Function(c As Char)
Return New String(New Char() {c})
End Function)
End If
If (allowRepetition) Then
Return PermuteCharacters(charSet, length:=length - 1, allowRepetition:=True).
AsParallel.AsOrdered.
SelectMany(Function(str As String)
Return charSet
End Function,
Function(str As String, c As Char)
Return str & c
End Function)
Else
Return PermuteCharacters(charSet, length:=length - 1, allowRepetition:=False).
AsParallel.AsOrdered.
SelectMany(Function(x As String) charSet,
Function(str As String, c As Char)
If Not str.Contains(c) Then
Return str & c
Else
Return Nothing
End If
End Function).
Where(Function(value As String) value IsNot Nothing)
End If
End Function
这个简单的代码来测试:
Dim permutations As IEnumerable(Of String) =
PermuteCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 5, allowRepetition:=True)
File.WriteAllLines("C:\test.txt", permutations)
没有并行性需要约。 10秒。
使用并行性需要约。 50秒。
我想了解为什么会发生这种情况,以及如何修复/改进它?。