using System;
using System.Diagnostics;
using System.Threading;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Collections.Generic;
namespace MultiCore
{ class ComplexCalc
{ static void Main(string[] args)
{ int MAX_COUNT = 1000;
Dictionary<int, byte[]> pool = new Dictionary<int, byte[]>();
Random rnd = new Random();
for (int i = 0; i < MAX_COUNT; i++)
{ byte[] b = new byte[512 * 1024];
rnd.NextBytes(b);
pool.Add(i, b);
}
int ROUND_COUNT = 5;
Stopwatch sw = new Stopwatch();
for (int WORKER_COUNT = 1; WORKER_COUNT < 16; WORKER_COUNT++)
{ long sum = 0;
List<string> detail = new List<string>();
for (int round = 0; round < ROUND_COUNT; round++)
{ sw.Reset();
sw.Start();
Thread[] workers = new Thread[WORKER_COUNT];
int jobsCountPerWorker = MAX_COUNT / WORKER_COUNT;
for (int i = 0; i < WORKER_COUNT; i++)
{ int st = jobsCountPerWorker * i;
int ed = jobsCountPerWorker * (i + 1);
if (ed > MAX_COUNT) ed = MAX_COUNT;
workers[i] = new Thread(() =>
{ DESCryptoServiceProvider des =
new DESCryptoServiceProvider();
des.Key = Encoding.UTF8.GetBytes("ABCDEFGH"); des.Key = Encoding.UTF8.GetBytes("12345678"); for (int j = st; j < ed; j++)
{ byte[] randomContent = pool[j];
using (MemoryStream ms = new MemoryStream())
{ using (CryptoStream cs = new CryptoStream(ms,
des.CreateEncryptor(), CryptoStreamMode.Write))
{ cs.Write(randomContent, 0, randomContent.Length);
cs.FlushFinalBlock();
}
}
}
});
workers[i].Start();
}
for (int i = 0; i < WORKER_COUNT; i++)
workers[i].Join();
sw.Stop();
sum += sw.ElapsedMilliseconds;
detail.Add(sw.ElapsedMilliseconds.ToString());
}
Console.WriteLine("平行處理[{1}] = {0:N0}ms [{2}]", sum / ROUND_COUNT, WORKER_COUNT, string.Join(",", detail.ToArray())); }
Console.Read();
}
}
}