' Collection of code snippets by Arne Vajhøj 
' (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
﻿Imports System
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks

Namespace T
    ''' <summary>
    ''' Demo class for comp.os.vms post.
    ''' </summary>
    Public Class Program
        ''' <summary>
        ''' Data holder class with:
        '''    array reference
        '''    start index and end index of slice
        '''    result sum of elements in slice
        ''' </summary>
        Public Class SumTask
            Public Property X() As Double()
            Public Property IxStart() As Integer
            Public Property IxEnd() As Integer
            Public Property Result() As Double
            Public Sub New(_X As Double(), _IxStart As Integer, _IxEnd As Integer)
                X = _X
                IxStart = _IxStart
                IxEnd = _IxEnd
            End Sub
            ''' <summary>
            ''' Calculate sum for slice using for loop.
            ''' </summary>
            Public Sub Run()
                Dim temp As Double() = X
                Dim ix1 As Integer = IxStart
                Dim ix2 As Integer = IxEnd
                Dim res As Double = 0
                For i As Integer = ix1 To ix2 - 1
                    res += temp(i)
                Next
                Result = res
            End Sub
        End Class
        ''' <summary>
        ''' Sum array using a for loop.
        ''' </summary>
        ''' <param name="x">array</param>
        ''' <returns>sum</returns>
        Private Shared Function ManSeq(x As Double()) As Double
            Dim res As Double = 0
            For i As Integer = 0 To x.Length - 1
                res += x(i)
            Next
            Return res
        End Function
        ''' <summary>
        ''' Sum array using 4 threads each processing 1/4 of the array.
        ''' </summary>
        ''' <param name="x">array</param>
        ''' <returns>sum</returns>
        Private Shared Function ManThread(x As Double()) As Double
            Dim t As Thread() = New Thread(3) {} ' array size must be multipla of number of threads to get slices defined correct
            Dim st As SumTask() = New SumTask(t.Length - 1) {}
            For k As Integer = 0 To t.Length - 1
                ' define slice and start thread 
                st(k) = New SumTask(x, k * x.Length \ t.Length, (k + 1) * x.Length \ t.Length)
                t(k) = New Thread(AddressOf st(k).Run)
                t(k).Start()
            Next
            Dim res As Double = 0
            For k As Integer = 0 To t.Length - 1
                ' wait for thread to complete and add sums
                t(k).Join()
                res += st(k).Result
            Next
            Return res
        End Function
        ''' <summary>
        ''' Sum array by submitting tasks to a thread pool (thread managed by pool).
        ''' </summary>
        ''' <param name="x">array</param>
        ''' <returns>sum</returns>
        Private Shared Function ManPool(x As Double()) As Double
            Dim t As Task() = New Task(15) {} ' array size must be multipla of number of tasks to get slices defined correct
            Dim st As SumTask() = New SumTask(t.Length - 1) {}
            For k As Integer = 0 To t.Length - 1
                ' define slice and and submit task
                st(k) = New SumTask( x, k * x.Length \ t.Length, (k + 1) * x.Length \ t.Length)
                t(k) = Task.Factory.StartNew(AddressOf st(k).Run)
            Next
            Dim res As Double = 0
            For k As Integer = 0 To t.Length - 1
                ' wait for task to complete and add sums
                t(k).Wait()
                res += st(k).Result
            Next
            Return res
        End Function
        ''' <summary>
        ''' Sum array using LINQ sum method - sequential (single threaded).
        ''' </summary>
        ''' <param name="x">array</param>
        ''' <returns>sum</returns>
        Private Shared Function LinqSeq(x As Double()) As Double
            Return x.Sum()
        End Function
        ''' <summary>
        ''' Sum array using LINQ sum method - parallel (multi threaded using thread pool).
        ''' </summary>
        ''' <param name="x"></param>
        ''' <returns></returns>
        Private Shared Function LinqPar(x As Double()) As Double
            Return x.AsParallel().Sum()
        End Function
        Private Const N As Integer = 100000000
        Private Const M As Integer = 10
        Private Const REP As Integer = 5
        Private Delegate Function Summer(x As Double()) As Double
        ''' <summary>
        ''' Test sum function.
        ''' </summary>
        ''' <param name="lbl">label</param>
        ''' <param name="sumf">sum function</param>
        ''' <param name="x">array</param>
        Private Shared Sub Test(lbl As String, sumf As Summer, x As Double())
            Dim dt1 As DateTime = DateTime.Now
            For j As Integer = 0 To M - 1
                Dim res As Double = sumf(x)
                ' for such a big array we should end up between 0.49 and 0.51
                If res < 0.49 * N OrElse 0.51 * N < res Then
                    Throw New Exception("We have a bad RNG")
                End If
            Next
            Dim dt2 As DateTime = DateTime.Now
            Console.WriteLine("{0,-20} : {1,5:F0}", lbl, (dt2 - dt1).TotalMilliseconds)
        End Sub
        Private Shared ReadOnly rng As New Random()
        ''' <summary>
        ''' Main program.
        ''' </summary>
        ''' <param name="args">-</param>
        Public Shared Sub Main(args As String())
            Dim x As Double() = New Double(N - 1) {}
            For i As Integer = 0 To x.Length - 1
                x(i) = rng.NextDouble()
            Next
            For j As Integer = 0 To REP - 1
                Test("Manual sequential", AddressOf ManSeq, x)
                Test("Manual threading", AddressOf ManThread, x)
                Test("Manual thread pool", AddressOf ManPool, x)
                Test("LINQ sequential", AddressOf LinqSeq, x)
                Test("LINQ parallel", AddressOf LinqPar, x)
                Console.WriteLine("----")
            Next
        End Sub
    End Class
End Namespace
