運行某些執行並行計算的代碼時,輸出會變成亂碼:不同的消息會混淆在一起。下面是一個示例:爲什麼在進行並行計算時打印到控制檯會混淆?
Iteration 1
Iteration
Iteration 23 of 19 - Calculating P&L for test window ending at 10/28/1968 12:00:00 AM
of
Iteration 4
Iteration of
Iteration 5
Iteration
Iteration 19 - Calculating P&L for test window ending at of 19 - Calculating P&L for test window ending at 5/29/1974 12:00:00 AM
6 of 878/18/1971 12:00:00 AM19 - Calculating P&L for test window ending at 3/4/1977 12:00:00 AM
of 19 of
of 19 - Calculating P&L for test window ending at 6/25/1985 12:00:00 AM
當運行程序順序相同的控制檯輸出出來漂亮,沒有錯亂。
let windowTrainTest (comm: Communication) critFoo count (model: IModel) (assets: Assets) (paramList: Parameters list) =
// Deleted some code here
if comm = Verbose then
let msg1 = sprintf "\nwindowTrainTestPandL: First date: %A, Last date: %A\nBest Criterion: %.2f\n" fDate lDate bestCriterion
let msg2 = sprintf "Best Parameters: %A\n" bestParameters
printfn "%s" <| msg1 + msg2
(pandl, wgts), bestParameters, (["Criterion", bestCriterion] |> Map.ofList,
["FirstDate", fDate; "LastDate", lDate] |> Map.ofList)
並行是由程序的這一部分進行:
打印到控制檯通過這個函數來完成
let pSeqMapi f (xs: seq<'T>) = xs |> PSeq.mapi f
let trainTest n i (trainSize, fullSize) =
let takenAssets = assets |> Assets.take (min fullSize len)
lastDate takenAssets
|> printfn "\nIteration %d of %d - Calculating P&L for test window ending at %A\n" (i + 1) n
paramList
|> windowTrainTest comm' critFoo trainSize model takenAssets
let mapTrainTest (initSizes: (int * int) list) =
let f = trainTest initSizes.Length
match calcType with
| PSeq -> initSizes |> pSeqMapi f |> List.ofSeq
| _ -> initSizes |> Seq.mapi f |> List.ofSeq
是否有辦法避免這種行爲,對例如通過刷新消息到控制檯?
我認爲這是因爲'printfn'%s「msg'與C#中的'Console.WriteLine(msg)'相當。雖然'printfn「%d的\ nIteration%d - 計算盈虧在結束%A \ n個測試窗口」(我+ 1)N'會像multple調用'Console.Write' 寫入控制檯是線程安全的,因此我認爲結果。 – xuanduc987