CSharp · Console
using System;
using System.Threading;
using System.Diagnostics;
const int N = 5_000;
var tab = CréerTableau(N * N);
for(int i = 1; i <= 16; ++i)
{
var (r, dt) = Tester(() => CompterMT(i, tab));
Console.WriteLine($"{i} fil(s) : compté {r} impairs en {dt} ms");
}
static short[] CréerTableau(int n)
{
short[] tab = new short[n];
for (int i = 0; i != tab.Length; ++i)
tab[i] = (short)(i * 2 + 1);
return tab;
}
static int CompterSi<T>(T[] tab, Func<T, bool> pred, int début, int fin) // début inclus, fin exclue
{
int n = 0;
for (int i = début; i != fin; ++i)
if (pred(tab[i]))
++n;
return n;
}
static (T rés, long dt) Tester<T>(Func<T> f)
{
var sw = new Stopwatch();
sw.Start();
T rés = f();
sw.Stop();
return (rés, sw.ElapsedMilliseconds);
}
static int CompterMT(int nbThreads, short [] tab)
{
int[] nbImpairs = new int[nbThreads]; // initialisé à 0 en C#
int tailleBloc = tab.Length / nbThreads;
Thread[] thrs = new Thread[nbThreads - 1];
for(int i = 0; i != thrs.Length; ++i)
{
int index = i;
int début = index * tailleBloc;
int fin = début + tailleBloc;
thrs[index] = new Thread(() =>
{
int nb = 0;
for (int j = début; j != fin; ++j)
if (tab[j] % 2 != 0)
nb++;
nbImpairs[index] = nb;
});
}
foreach (var th in thrs) th.Start();
////
{
int début = (nbThreads - 1) * tailleBloc;
int fin = tab.Length;
int nb = 0;
for (int j = début; j != fin; ++j)
if (tab[j] % 2 != 0)
++nb;
nbImpairs[nbThreads - 1] = nb;
}
////
foreach (var th in thrs) th.Join();
int somme = 0;
foreach (int n in nbImpairs)
somme += n;
return somme;
}