예제 #1
0
        static void Main(string[] args)
        {
            /*Функция решает систему 4х4 вида:  [4, 1, 1, 1]
             *                                  [1, 4, 1, 1]
             *                                  [1, 1, 4, 1]
             *                                  [1, 1, 1, 4]
             * с единичным вектором правой части
             */
            //Test();


            TestTime test_time = new TestTime();
            //Имя файла для загрузки и сохранения
            string filename = "people.dat";

            TestTime.Load(filename, ref test_time);

            while (true)
            {
                try
                {
                    //Вводим порядок матрицы
                    Console.WriteLine("Введите порядок матрицы или 'end' для выхода: ");
                    string str = Console.ReadLine();
                    if (str == "end")
                    {
                        break;
                    }
                    else
                    {
                        int a = Convert.ToInt32(str);

                        TestTimeItem test_time_item = new TestTimeItem();

                        test_time_item.calculateCoef(a);
                        test_time.Add(test_time_item);
                    }
                }
                catch (System.IO.IOException ex)
                {
                    Console.WriteLine(ex.Message);
                    break;
                }
                catch (FormatException ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine("Необходимо ввеcти число или 'end'\n");
                }
            }

            TestTime.Save(filename, test_time);
            Console.Write(test_time);

            /*foreach (var ass in AppDomain.CurrentDomain.GetAssemblies())
             *  foreach (var type in ass.GetTypes())
             *      if (type.IsSubclassOf(typeof(Exception)))
             *          Console.WriteLine(type);
             */
            System.Threading.Thread.Sleep(5000);
        }
예제 #2
0
    static void Main(string[] args)
    {
        try
        {
            Test();
            TestTime tt = new TestTime();
            TestTime.Load("result", ref tt);

            Console.WriteLine("Конец ввода - q");
            while (true)
            {
                Console.Write("Порядок блочной матрицы: ");
                try
                {
                    string input = Console.ReadLine();
                    if (input == "q")
                    {
                        break;
                    }
                    int blocks = Convert.ToInt32(input);
                    if (blocks <= 0)
                    {
                        throw new Exception();
                    }

                    Console.Write("Порядок матриц-элементов: ");
                    input = Console.ReadLine();
                    if (input == "q")
                    {
                        break;
                    }
                    int smallOrder = Convert.ToInt32(input);
                    if (smallOrder <= 0)
                    {
                        throw new Exception();
                    }

                    double msSharp = 0.0, msPlus = 0.0;
                    GenerateAndSolve(blocks, smallOrder, ref msSharp, ref msPlus);
                    string s = "Порядок блочной матрицы: " + blocks.ToString() +
                               "\nПорядок матриц-элементов: " + smallOrder.ToString() +
                               "\nВремя на C#: " + msSharp.ToString() +
                               "\nВремя на C++: " + msPlus.ToString() +
                               "\nОтношение: " + (msSharp / msPlus).ToString() + "\n";
                    tt.Add(s);
                }
                catch (Exception)
                {
                    Console.WriteLine("Неправильный ввод\n");
                }
            }

            Console.WriteLine("==================================");
            Console.WriteLine(tt);
            TestTime.Save("result", tt);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
예제 #3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Pyatov Vladislav - 301 group.");

            //подготовка
            if (Directory.Exists(@"c:\Lab5_Pyatov"))
            {
                try
                {
                    File.Delete(@"c:\Lab5_Pyatov\C#_test.txt");
                    File.Delete(@"c:\Lab5_Pyatov\C++_test.txt");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Delete exception: " + ex.Message);
                }
            }

            Test();
            TestTime t = new TestTime();

            TestTime.Load(@"c:\Lab5_Pyatov\TestTime.txt", ref t);

            int N, blockN;

            Console.WriteLine("Press any key to start programm or <Escape> to exit\n");
            while (Console.ReadKey().Key != ConsoleKey.Escape)
            {
                try
                {
                    string s = "";
                    Console.WriteLine("Enter Matrix order:");
                    N = Convert.ToInt32(Console.ReadLine());
                    if (N < 1)
                    {
                        throw new ArgumentException("Matrix order should be greater then zero");
                    }
                    Console.WriteLine("Enter block order:");
                    blockN = Convert.ToInt32(Console.ReadLine());
                    if (blockN < 1)
                    {
                        throw new ArgumentException("Block order should be greater than zero");
                    }
                    s += "Matrix order = " + N + ", block order = " + blockN + ", ";

                    //Вычисление на С#
                    blockmatrix b_matrix  = new blockmatrix(N, blockN);
                    vectorb     b_vector  = new vectorb(N, blockN, true);
                    Stopwatch   stopwatch = new Stopwatch();

                    stopwatch.Start();
                    vectorb ans = b_matrix.SLAU(b_vector);
                    stopwatch.Stop();

                    //Сохранение
                    b_matrix.save(ans, b_vector);

                    double time_Csharp = stopwatch.ElapsedMilliseconds;
                    s += "C# time = " + (stopwatch.ElapsedMilliseconds).ToString() + "ms , ";

                    //Вычисление на С++
                    //перевод вектора правой части в массив
                    double[] b = new double[b_vector.GetBlockN * b_vector.GetN];
                    int      n = 0;
                    for (var i = 0; i < b_vector.GetN; i++)
                    {
                        for (var j = 0; j < b_vector.GetBlockN; j++)
                        {
                            b[n++] = b_vector[i][j];
                        }
                    }

                    //перевод блочной 3-диагональной в один массив
                    double[] mat       = new double[b_matrix.GetblockN * 4 + 3 * b_matrix.GetblockN * (b_matrix.GetN - 2)];
                    int      mat_index = 0;

                    for (var j = 0; j < b_matrix.GetN; j++)
                    {
                        if (j != 0)
                        {
                            for (var i = 0; i < b_matrix.GetblockN; i++)
                            {
                                mat[mat_index] = b_matrix.A[j][i, i];
                                mat_index++;
                            }
                        }
                        for (var i = 0; i < b_matrix.GetblockN; i++)
                        {
                            mat[mat_index] = b_matrix.C[j][i, i];
                            mat_index++;
                        }
                        if (j != b_matrix.GetN - 1)
                        {
                            for (var i = 0; i < b_matrix.GetblockN; i++)
                            {
                                mat[mat_index] = b_matrix.B[j][i, i];
                                mat_index++;
                            }
                        }
                    }

                    //объявление массива решения
                    double[] x = new double[b_vector.GetN * b_vector.GetBlockN];

                    //Решение системы на С++
                    double time = -1;
                    F(mat, x, b, b_vector.GetN, b_vector.GetBlockN, ref time);

                    //приведение массива решения к типу вектор
                    vectorb output = new vectorb(x, b_vector.GetN, b_vector.GetBlockN);

                    s += "C++ time = " + time.ToString() + "ms, ratio(C#/C++) = " + (time > 0?time_Csharp / time:0) + ";";

                    //Добавление в TestTime
                    t.Add(s);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                Console.WriteLine("Press any key to continue or <Escape> to exit");
            }
            Console.WriteLine(t);
            TestTime.Save(@"c:\Lab5_Pyatov\TestTime.txt", t);
        }
예제 #4
0
        static void Main(string[] args)
        {
            Test();
            Console.WriteLine();

            TestTime log = new TestTime();

            if (TestTime.Load(logFilename, ref log) == false)
            {
                Console.WriteLine("Не получилось загрузить лог; будет создан пустой лог.");
                Console.WriteLine();
            }

            Console.WriteLine("Данная программа сравнивает время решения линейных уравнений с блочной трёхдиагональной матрицей в коде на C# и на C++.");
            Console.WriteLine();

            bool continueTests = true;

            while (continueTests)
            {
                Console.WriteLine("Провести тест? Введите 'y' для продолжения, 'n' для выхода из программы");
                string userInput = Console.ReadLine();
                Console.WriteLine();

                if (userInput == "n")
                {
                    continueTests = false;
                }
                else if (userInput != "y")
                {
                    Console.WriteLine("Команда введена с ошибками; возврат в главное меню.");
                    Console.WriteLine();
                    continue;
                }
                else
                {
                    int matDim, bloDim;  // Dimensions

                    Console.WriteLine("Введите блочный порядок матрицы (количество блоков вдоль каждой из сторон матрицы):");
                    try  // Getting matrix dimension
                    {
                        matDim = int.Parse(Console.ReadLine());
                        if (matDim < 2)
                        {
                            throw new ArgumentException("Порядок матрицы должен быть натуральным числом, не меньшим 2.");
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Порядок блочной матрицы введён с ошибками");
                        Console.WriteLine();
                        Console.WriteLine($"Сообщение об ошибке: {e.Message}");
                        Console.WriteLine();
                        continue;
                    }

                    Console.WriteLine("Введите порядок блока (количество чисел вдоль каждой из сторон блока):");
                    try  // Getting block dimension
                    {
                        bloDim = int.Parse(Console.ReadLine());
                        if (bloDim < 1)
                        {
                            throw new ArgumentException("Порядок блока должен быть натуральным числом, не меньшим 1.");
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Порядок блока введён с ошибками");
                        Console.WriteLine();
                        Console.WriteLine($"Сообщение об ошибке: {e.Message}");
                        Console.WriteLine();
                        continue;
                    }

                    // Preparations

                    double[] rightSide = null;
                    double   csTime = 0, cppTime = 0;
                    double[] csResult  = null;
                    double[] cppResult = null;

                    try  // Allocating memory
                    {
                        rightSide = new double[matDim * bloDim];
                        for (int i = 0; i < rightSide.Length; ++i)
                        {
                            rightSide[i] = 1;
                        }
                        csResult  = new double[rightSide.Length];
                        cppResult = new double[rightSide.Length];
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Не удалось выделить память под массивы правой части/решений. Вероятно, были указаны слишком большие размеры матрицы.");
                        Console.WriteLine();
                        Console.WriteLine($"Сообщение об ошибке: {e.Message}");
                        Console.WriteLine();
                        continue;
                    }

                    BlockMatrix mat;
                    try  // C# solution
                    {
                        mat = new BlockMatrix(matDim, bloDim);
                        Stopwatch watch = new Stopwatch();

                        try
                        {
                            watch.Start();
                            BlockMatrix.SolveSystem(mat, rightSide, csResult);
                            watch.Stop();
                        }
                        catch (ArithmeticException e)
                        {
                            Console.WriteLine("К сожалению, к данной матрице метод прогонки неприменим. Попробуйте взять матрицу с диагональным преобладанием.");
                            Console.WriteLine();
                            Console.WriteLine($"Сообщение об ошибке: {e.Message}");
                            Console.WriteLine();
                            continue;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            continue;
                        }
                        finally
                        {
                            watch.Stop();
                        }

                        csTime = watch.ElapsedMilliseconds;
                        Console.WriteLine($"Решение на C# успешно завершилось за {csTime} миллисекунд.");
                        Console.WriteLine();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Something broke unexpectedly: {e.Message}");
                        if (e.InnerException != null)
                        {
                            Console.WriteLine(e.InnerException.Message);
                        }

                        continue;
                    }

                    try  // CPP solution
                    {
                        SolveEquationCpp(matDim, bloDim, mat.ToPlainArray(), rightSide, cppResult, ref cppTime);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Something broke unexpectedly: {e.Message}");
                        if (e.InnerException != null)
                        {
                            Console.WriteLine(e.InnerException.Message);
                        }

                        continue;
                    }

                    double ratio = (cppTime > 0) ? ((double)csTime) / cppTime : -1;

                    log.Add(TestTime.FormatString(matDim, bloDim, csTime, cppTime, ratio));
                }
            }

            if (TestTime.Save(logFilename, log) == false)
            {
                Console.WriteLine("Не получилось сохранить лог; результаты данного запуска программы не сохранены.");
            }

            Console.WriteLine("Завершаем работу программы. Содержимое журнала:");
            Console.WriteLine();

            Console.WriteLine(log);

            Console.WriteLine("Нажмите ENTER для завершения...");
            Console.ReadLine();
        }
예제 #5
0
        static void Main(string[] args)
        {
            Test();
            bool flag = false;
            char symbol;


            while (!flag)
            {
                Console.WriteLine("Завершить работу? (y/n)");
                Console.Write("  ");
                symbol = Console.ReadKey().KeyChar;
                Console.WriteLine();
                if (symbol == 'y')
                {
                    return;
                }
                if (symbol == 'n')
                {
                    flag = true;
                }
                if (symbol != 'n')
                {
                    Console.WriteLine("Недопустимый символ !");
                }
            }


            TestTime obj = new TestTime();

            TestTime.Load(@"C:\Users\Маша\Documents\Visual Studio 2017\Projects\Lab_5_Masha\TestTime.txt", ref obj);

            flag = true;

            while (flag)
            {
                Console.WriteLine("Введите порядок матрицы :");
                Console.Write("  ");
                try
                {
                    m_size = Int32.Parse(Console.ReadLine());
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Исключение : " + ex.Message);
                    continue;
                }

                if (m_size >= 2)
                {
                    double[] solution = new double[m_size * 3];

                    double[] matr_data = new double[m_size * m_size * 9];

                    for (int i = 0; i < m_size * m_size * 9; ++i)
                    {
                        matr_data[i] = i + 1;
                    }

                    double[] F_data = new double[m_size * 3];

                    for (int i = 0; i < m_size * 3; ++i)
                    {
                        F_data[i] = i + 1;
                    }

                    Stopwatch swatch = new Stopwatch();
                    swatch.Start();

                    Block3DMatrix matr = new Block3DMatrix(matr_data, F_data, m_size);

                    matr.solve();

                    swatch.Stop();

                    export_function(matr_data, F_data, m_size, solution, ref work_time_cpp);

                    obj.Add(m_size.ToString(),
                            (swatch.Elapsed.Milliseconds).ToString(),
                            work_time_cpp.ToString(),
                            ((double)swatch.Elapsed.Milliseconds / (double)work_time_cpp).ToString());
                }


                else
                {
                    Console.WriteLine("Недопустимый размер матрицы !");
                    continue;
                }

                Console.WriteLine("Продолжить? (y/n)");
                Console.Write("  ");
                symbol = Console.ReadKey().KeyChar;
                Console.WriteLine();
                if (symbol == 'n')
                {
                    flag = false;
                }
                else
                {
                    if (symbol != 'y')
                    {
                        Console.WriteLine("Недопустимый символ !");
                        flag = false;
                    }
                }
            }
            TestTime.Save(@"C:\Users\Маша\Documents\Visual Studio 2017\Projects\Lab_5_Masha\TestTime.txt", ref obj);
            Console.WriteLine(obj);
        }
 void _timer_Elapsed(object sender, ElapsedEventArgs e)
 {
     TestTime = TestTime.Add(new TimeSpan(0, 0, 0, 0, (int)_timer.Interval));
 }