Параллельный генератор псевдослучайных чисел, на базе четырех линейных конгруэнтных генераторов - C#

Узнай цену своей работы

Формулировка задачи:

Всем доброе время суток)) У меня такая задачка: Нужно реализовать параллельный генератор псевдослучайных чисел, на базе четырех линейных конгруэнтных генераторов и распараллелить их. Я все сделал и прога работает. Но ускорения не получается. Т.е. на 1 потоке выходит, что работает быстрей чем на 4. Почему?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
 
namespace palg_5._2
{
    class NewThread
    {
        List<int> on_ArrayThread;
        List<int> two_ArrayThread;
        List<int> three_ArrayThread;
        List<int> four_ArrayThread;
        StringBuilder onArrayThread;
        Stopwatch timeStopwatch1;
        Stopwatch timeStopwatch2;
        Stopwatch timeStopwatch3;
        Stopwatch timeStopwatch4;
        Stopwatch timeStopwatch5;
        List<int> fourArrayThread;
        int a1, a2, a3, a4;
        int c1, c2, c3, c4;
        int m1, m2, m3, m4;
        int n1, n2, n3, n4;
        public long on_time, four_time;
 
        public NewThread(int a1, int c1, int m1, int n1, int a2, int c2, int m2, int n2,
            int a3, int c3, int m3, int n3, int a4, int c4, int m4, int n4)
        {
            this.a1 = a1; this.c1 = c1; this.m1 = m1; this.n1 = n1;
            this.a2 = a2; this.c2 = c2; this.m2 = m2; this.n2 = n2;
            this.a3 = a3; this.c3 = c3; this.m3 = m3; this.n3 = n3;
            this.a4 = a4; this.c4 = c4; this.m4 = m4; this.n4 = n4;
 
            timeStopwatch1 = new Stopwatch();
            timeStopwatch2 = new Stopwatch();
            timeStopwatch3 = new Stopwatch();
            timeStopwatch4 = new Stopwatch();
            timeStopwatch5 = new Stopwatch();
 
            on_ArrayThread = new List<int>();
            two_ArrayThread = new List<int>();
            three_ArrayThread = new List<int>();
            four_ArrayThread = new List<int>();
            onArrayThread = new StringBuilder();
            fourArrayThread = new List<int>();
        }
        private List<int> Generator(int a, int c, int m, int n, List<int> buf)
        {
            int i = 0;
            buf = new List<int>();
            buf.Add(n);
            while (true)
            {
                buf.Add((a * buf[i] + c) % m);
                if (buf[i + 1] == n) { break; }
                else i++;
            }
 
            return buf;
        }
        private void On_Array()
        {
            timeStopwatch1.Start();
            on_ArrayThread = Generator(a1, c1, m1, n1, on_ArrayThread);
            timeStopwatch1.Stop();
        }
        private void Two_Array()
        {
            timeStopwatch2.Start();
            two_ArrayThread = Generator(a2, c2, m2, n2, two_ArrayThread);
            timeStopwatch2.Stop();
        }
        private void Three_Array()
        {
            timeStopwatch3.Start();
            three_ArrayThread = Generator(a3, c3, m3, n3, three_ArrayThread);
            timeStopwatch3.Stop();
        }
        private void Four_Array()
        {
            timeStopwatch4.Start();
            four_ArrayThread = Generator(a4, c4, m4, n4, four_ArrayThread);
            timeStopwatch4.Stop();
        }
        private void On_Thread()
        {
            if (on_ArrayThread != null)
                on_ArrayThread.Clear();
            if (two_ArrayThread != null)
                two_ArrayThread.Clear();
            if (three_ArrayThread != null)
                three_ArrayThread.Clear();
            if (four_ArrayThread != null)
                four_ArrayThread.Clear();
            timeStopwatch5.Start();
            On_Array();
            Two_Array();
            Three_Array();
            Four_Array();
            timeStopwatch5.Stop();
        }
 
        //вызываем 4 потока
        public void All_Thread()
        {
            Thread onThread = new Thread(On_Array);
            Thread twoThread = new Thread(Two_Array);
            Thread threeThread = new Thread(Three_Array);
            Thread fourThread = new Thread(Four_Array); 
 
            onThread.Start();
            twoThread.Start();
            threeThread.Start();
            fourThread.Start();
 
            four_time = timeStopwatch1.ElapsedTicks + timeStopwatch2.ElapsedTicks +
                timeStopwatch3.ElapsedTicks + timeStopwatch4.ElapsedTicks;
            /*while (onThread.IsAlive == true) { }
            while (twoThread.IsAlive == true) { }
            while (threeThread.IsAlive == true) { }
            while (fourThread.IsAlive == true) { }*/
        }        
        //вызываем 1 поток
        public void Create_On_thread()
        {
            Thread newThread = new Thread(On_Thread);
            newThread.Start();
            while (newThread.IsAlive == true) { }
            on_time = timeStopwatch5.ElapsedTicks;
        }
        //складываем все в одну переменную
        public void FourArrayToOnArray()
        {
            int i = 0;
            do
            {
                fourArrayThread.Add(on_ArrayThread[i]); i++;
            }
            while (i != on_ArrayThread.Count);
 
            int j = 0;
            do
            {
                fourArrayThread.Add(two_ArrayThread[j]); j++;
            }
            while (j != two_ArrayThread.Count);
            int k = 0;
            do
            {
                fourArrayThread.Add(three_ArrayThread[k]); k++;
            }
            while (k != three_ArrayThread.Count);
            int c = 0;
            do
            {
                fourArrayThread.Add(four_ArrayThread[c]); c++;
            }
            while (c != four_ArrayThread.Count);
        }
        //переводим в 2-ю систему
        public String ArrayToString()
        {
            String buffer = String.Empty;
            String str = String.Empty;
            StringBuilder buf = new StringBuilder();
            for (int i = 0; i < fourArrayThread.Count; i++)
            {
                str = Convert.ToString(fourArrayThread[i], 2);
 
                for (int l = 7; l >= 0; l--)
                {
                    if (l <= str.Length - 1)
                        buf.Insert(8 - str.Length, str[l]);
                    else buf.Append(0);
                }
                buffer += buf.ToString();
                buf.Clear();
            }
            return buffer;
        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace palg_5._2
{
    public partial class Form1 : Form
    {
        DateTime oldtime_on;
        DateTime oldtime_four;
        long time_on;
        long time_four;
        NewThread myThread;
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                richTextBox1.Clear();
 
                myThread = new NewThread(Int32.Parse(textBox1.Text), Int32.Parse(textBox8.Text), Int32.Parse(textBox12.Text), Int32.Parse(textBox16.Text),
                    Int32.Parse(textBox2.Text), Int32.Parse(textBox7.Text), Int32.Parse(textBox11.Text), Int32.Parse(textBox15.Text),
                    Int32.Parse(textBox3.Text), Int32.Parse(textBox6.Text), Int32.Parse(textBox10.Text), Int32.Parse(textBox14.Text),
                    Int32.Parse(textBox4.Text), Int32.Parse(textBox5.Text), Int32.Parse(textBox9.Text), Int32.Parse(textBox13.Text));
 
                //oldtime_four = DateTime.Now;
                myThread.All_Thread();
                //time_four = DateTime.Now.Ticks - oldtime_four.Ticks;
                richTextBox1.Text += "Time 4 thread: " + myThread.four_time + "\n";
 
                //oldtime_on = DateTime.Now;
                myThread.Create_On_thread();
                //time_on = DateTime.Now.Ticks - oldtime_on.Ticks;
                richTextBox1.Text += "Time 1 thread: " + myThread.on_time + "\n";
 
                richTextBox1.Text += "Speed: " + ((double)myThread.on_time / (double)myThread.four_time) + "\n";
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex);
            }
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                myThread.FourArrayToOnArray();
                String buffer = myThread.ArrayToString();
                richTextBox1.Text += buffer;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex);
            }
        }
 
        private void button3_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }
    }
}

Решение задачи: «Параллельный генератор псевдослучайных чисел, на базе четырех линейных конгруэнтных генераторов»

textual
Листинг программы
while (true)
            {
                buf.Add((a * buf[i] + c) % m); //генерится следующий эл. последовательности
                if (buf[i + 1] == n) { break; } //если он равен первому, то выходим
                else i++; //иначе просто продолжаем
            }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

9   голосов , оценка 3.778 из 5
Похожие ответы