Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- open System;
- open System.Diagnostics;
- open System.Threading; // для ThreadLocal
- module SafeRandom =
- let private rnd = new Random()
- let New() =
- lock rnd (fun () ->
- new Random(rnd.Next()))
- #if !NET20
- type ThreadSafeRandom() =
- let r = new ThreadLocal<Random>(fun _ -> SafeRandom.New())
- member _.Next = r.Value.Next
- interface IDisposable with
- member _.Dispose() = r.Dispose()
- #endif
- #if NET20
- type ThreadSafeRandom() =
- [<ThreadStatic>]
- [<DefaultValue>]
- static val mutable private r: Random
- member _.Next =
- if ThreadSafeRandom.r = null then
- ThreadSafeRandom.r <- SafeRandom.New()
- ThreadSafeRandom.r.Next
- interface IDisposable with // для совместимости с более новой версией
- member _.Dispose() = ()
- #endif
- #if NET20
- module Array =
- module Parallel =
- let map f (arr: _[]) =
- let len = arr.GetLength(0)
- let res = Array.zeroCreate len
- let loop i =
- let start = (i*len)/Environment.ProcessorCount
- let finish = ((i+1)*len)/Environment.ProcessorCount - 1
- for j in start .. finish do
- res.[j] <- f(arr.[j])
- Async.Parallel [ for i in 0..Environment.ProcessorCount-1 -> async {do loop(i)} ]
- |> Async.Ignore
- |> Async.RunSynchronously
- res
- #endif
- [<EntryPoint>]
- let main _ =
- use random = new ThreadSafeRandom()
- let randomStr =
- let chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
- let charsLen = chars.Length
- fun len ->
- let randomChars = [|for _ in 0..len-1 -> chars.[random.Next(charsLen)]|]
- new string(randomChars)
- let randomString100(_) = randomStr(100)
- let randomString20() = randomStr(20)
- for _ in 1..10 do
- let stopWatch = Stopwatch.StartNew()
- let listString100 = Array.init 100000 randomString100
- let matches =
- [|1..1000|]
- |> Array.Parallel.map (fun _ ->
- let s20 = randomString20()
- listString100
- |> Array.exists (fun s100 -> s100.Contains(s20))
- |> fun exists -> if exists then 1 else 0)
- |> Array.sum
- printfn "%d strings matches, time = %f"
- matches stopWatch.Elapsed.TotalMilliseconds
- 0 // return an integer exit code
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement