Single or Parallel – for.loops test – Visual Studio 2010

ParallelWon  SingleAndParallel Single

 Una de las novedades más excitantes de Visual Studio 2010 y el Framework, sin duda es la incorporación de las librerías para el uso de la ejecución en paralelo “paralelismo” o TPL (Task Parallel Library), pudiendo por fin sacar provecho a los ya extendidos multiprocesadores y/o múltiples ‘cores’.

Parece sencillo pero… no esta tan claro.

Es evidente que el uso de un simple ‘Parallel.For’ como cualquier otro proceso a través del framework, requiere de un número de recursos para conformar o organizar, planear y finalmente realizar la ejecución, además podemos suponer que este paralelismo se apoya sobre ‘threading’, por lo que debemos entender su aplicación dentro de escenarios donde exista un uso intensivo en la ejecución de tareas especificas y que estas justifiquen el consumo inicial de recursos en términos de rendimiento.

Con dichas conjeturas, está claro que un simple ‘for next’ siempre ganara en velocidad a un ‘parallel.for’,  si su ejecución se limita a la iteración sobre una simple estructura o lista y bien entendiendo en funciones cuya ejecución se realiza en una sola pasada.

Sin embargo la situación sufre un cambio radical cuando nuestro bucle itera en llamadas a funciones que realizan tareas con cierta carga de proceso.

Sin ninguna otra pretensión me complace compartir con vosotros un punto de entrada para evaluar la conveniencia o no de usar el paralelismo en determinadas tareas. También es evidente que no se trata de una herramienta formal, simplemente pretende ser un punto de entrada para experimentar de forma sencilla y asequible la implementación de escenarios muy básicos.

Esperando vuestras valoraciones, espero que llame vuestra atención y os complazca.

Cuidaros Mucho!
Pep Lluis,

Para probar la aplicación, necesitareis tener instalada la versión beta de Visual Studio 2010 y crear un nuevo proyecto ‘Windows Form Application’ deberemos añadir y distribuir en su form1 las siete etiquetas (del Label1 al Label7) correspondientes a la visualización de los datos del proceso, dos ‘NumericUpDown’ para proporcionarle el numero de bucles e iteraciones, un ‘Progressbar’ para comparar tiempos de ejecución y listo … con copiar y pegar el código adjunto, podréis utilizar este “tester” para vuestra primera aplicación en paralelo J

No dudéis en contactar conmigo si necesitáis cualquier aclaración o si necesitáis que os envíe el prototipo para este proyecto.

 With no doubt  one of the most exciting features in Visual Studio 2010 and Framework 4 is parallel computing or TPL (Task Parallel Library), being able finally to take benefit of multiprocessors  and multi core systems. 

This seems clear and simple but… may be need consider some aspects before J

It is evident that the use of simple Parallel.For’ like any other process through framework, requires a minimum number of resources to conform, to organize, to plan and finally to make the execution, in addition we can suppose that this parallelism leans on `threading’, reason why must be applied within scenes where have an intensive use of processes execution or long tasks, at end only this may justify these initial consumption of resources in performance terms.

With these conjectures, it is clear that simple `for next’ always won in speed to `parallel.for’, if their execution are limited to iterate on a simple structure or list, as well understanding this functions inside single flow process and made one to one.

Nevertheless the situation undergoes a radical change when our iteration calls to functions that make tasks with certain load of process.

Without any other pretension it pleases to me to share with you an entry point to evaluate the convenience of using parallelism in certain tasks. Also it is evident that one is not a formal tool, simply tries to be an entry point to start with a reasonable simple form and the implementation of very basic scenes.

Waiting for your evaluation, I hope this short explanation pleases to you.

Take care!
Pep Lluis,

Ps: No doubt in contacting with me if you need any extra explanation or if you need that I sent this prototype to you.

 

In this sample readings do not seem respond to the real milliseconds, I recommend use `ElapsedTicks’ instead `Elapsed.TotalMilliseconds”, these correspond directly to ticks of chrono, eliminating any other interpretation.

Regards,

Imports System.Threading

‘ Simple Skeleton to test ‘parallel.for’
‘ Pep Lluis 14.07.2009

‘ Compare/test time execution of single over parallel task’s

‘ To run require Visual Studio 2010 Beta
‘ To catch Illegal Cross threat’s exceptions, correct appropriate code
‘ or set false, Checking cross thread calls.

Public Class SingleOrParallel
    Dim _timer As New System.Timers.Timer
    Private Sub SingleOrParallel_Load() Handles MyBase.Load
        AddHandler _timer.Elapsed, AddressOf Testing    ‘Run Test every elapsed time
        _timer.Interval = 1000                          ‘elapsed time to 1s
        _timer.Enabled = True                           ‘run timer
    End Sub

    Dim Elapsed1, Elapsed2 As Double                    ‘define elapsed memory’s
    Sub Testing()
        _timer.Enabled = False                          ‘Stop timer
        Me.Label5.Text = «Running Test»
        loops = Me.NumericUpDown1.Value                 ‘read number of loops
        SequentialFor()                                 ‘Call Sequential for
        ParallelFor()                                   ‘Call Parallel for
       
        ‘ Show results
        If Elapsed1 > Elapsed2 Then
            Label3.ForeColor = Drawing.Color.Red        ‘Parallel won
            Label4.ForeColor = Drawing.Color.Green
            ‘show execution time & differences between parallel & single
            Me.ProgressBar1.Value = (Elapsed2 * 100 / Elapsed1)
            Label5.Text = «fast « + (100 – Int(Elapsed2 / Elapsed1 * 100)).ToString + «%»
            Label6.Text = Elapsed1.ToString             ‘Single time
            Label7.Text = Elapsed2.ToString             ‘Parallel time
        Else
            Label3.ForeColor = Drawing.Color.Green      ‘Single won
            Label4.ForeColor = Drawing.Color.Red
            Me.ProgressBar1.Value = (Elapsed1 * 100 / Elapsed2)
            Label5.Text = «fast « + (100 – Int(Elapsed1 / Elapsed2 * 100)).ToString + «%»
            Label6.Text = Elapsed2.ToString             ‘Parallel time
            Label7.Text = Elapsed1.ToString             ‘Single time
        End If
        ‘ put result bottom progressbar value
        Label7.Left = (Me.ProgressBar1.Left +
                      ((ProgressBar1.Width / ProgressBar1.Maximum) * ProgressBar1.Value)) –
                      (Label7.Width / 2)
        _timer.Enabled = True                           ‘start timer to next test
    End Sub

 

    Dim loops As Integer
    Dim Chrono As New Stopwatch

    Sub SequentialFor()
        Chrono.Start()              ‘Start watch
        ‘ Conventional for next
        For n = 0 To loops
            SomeTask()
        Next
        ‘ remember Elapsed time
        Elapsed1 = Chrono.Elapsed.TotalMilliseconds
        Chrono.Stop()               ‘Watch stop
        Chrono.Reset()              ‘reset!
    End Sub

    Sub ParallelFor()
        Chrono.Start()              ‘Start wath
        ‘ parallel for
        Parallel.For(0, loops, Sub(n)
                                   SomeTask()
                               End Sub)
        ‘ remember Elapsed time
        Elapsed2 = Chrono.Elapsed.TotalMilliseconds
        Chrono.Stop()               ‘Watch stop
        Chrono.Reset()              ‘reset!
    End Sub

   
    ‘Simulated task
    Sub SomeTask()
        ‘Your task here
        Thread.SpinWait(NumericUpDown2.Value)
    End Sub

End Class