本帖最后由 moy838840554 于 2024-8-28 10:55 编辑
当然,这个代码在你的电脑上跑效果可能没差别,得换到cpu核心数更多的电脑上跑
- int start = 1;
- int end = 50000;
- int processorCount = Environment.ProcessorCount/2; // 获取 CPU 核心数/2
- int range =end / processorCount; // 计算每个线程的范围
- #region 线程实现
- var sw1 = new Stopwatch();
- sw1.Start();
- Task<BigInteger>[] tasks = new Task<BigInteger>[processorCount];
- for (int i = 0; i < processorCount; i++)
- {
- int taskStart = start + i * range;
- int taskEnd = (i == processorCount - 1) ? end : taskStart + range - 1; // 确保最后一个任务处理到结束
- tasks = Task.Run(() => Calculate(taskStart, taskEnd));
- }
- // 等待所有任务完成
- Task.WaitAll(tasks);
- // 计算最终乘积
- BigInteger result1 = 1;
- foreach (var task in tasks)
- {
- result1 *= task.Result;
- }
- sw1.Stop();
- #endregion
- #region 常规实现
- var sw2 = new Stopwatch();
- sw2.Start();
- var result2 = Calculate(start, end);
- sw2.Stop();
- #endregion
- Env.Editor.WriteMessage($"\n 计算结果相等?{result1 == result2}" +
- $"\n 线程/常规(毫秒):{sw1.ElapsedMilliseconds}/{sw2.ElapsedMilliseconds}");
|