/// <summary> /// Run common tasks to setup the application /// </summary> public static void Setup() { Reports = new List <Report>(); if (!string.IsNullOrEmpty(ApplicationSettings.Instance.GnuplotFullPath)) { return; } ApplicationSettings.Instance.GnuplotFullPath = SystemHelper.GetProgramFilesX86Path(); if (ApplicationSettings.Instance.GnuplotFullPath != "") { ApplicationSettings.Instance.GnuplotFullPath += "\\gnuplot\\bin\\wgnuplot.exe"; } else // No windows { ApplicationSettings.Instance.GnuplotFullPath = "gnuplot"; } }
/// <summary> /// Generate Gnuplot graf files /// </summary> public static void GenerateGnuplotFiles() { try { if (!Directory.Exists(ApplicationSettings.Instance.ReportsPath)) { Directory.CreateDirectory(ApplicationSettings.Instance.ReportsPath); } using (TextWriter fstream = new StreamWriter(Path.Combine(ApplicationSettings.Instance.ReportsPath, Program.GNUPLOT_GENERATOR_FILE) + (SystemHelper.IsWindows() ? ".bat" : ".sh"))) { string gnuvar = "%GNUPLOT_PATH%"; if (SystemHelper.IsWindows()) { fstream.Write("@echo off\n" + "title \"Relatorio de grafos com GNUPLOT\"\n" + "set GNUPLOT_PATH=\"{0}\"\n", ApplicationSettings.Instance.GnuplotFullPath); } else { fstream.Write("echo \"Relatorio de grafos com GNUPLOT\"\n" + "GNUPLOT_PATH=\"{0}\"\n", ApplicationSettings.Instance.GnuplotFullPath); gnuvar = "$GNUPLOT_PATH"; } for (int i = 0; i < Program.ALGORTIHMS.Length; i++) { fstream.Write("echo Running {0} sort plot\n" + "{1} -p \"{0}.plt\"\n", Program.ALGORTIHMS[i], gnuvar); } fstream.Write("echo Running All sort plot\n" + "{0} -p \"All.plt\"\n", gnuvar); fstream.Write("\npause"); fstream.Close(); } } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary> /// Run a algorithm and log execution /// </summary> /// <param name="classname">Class name</param> /// <param name="method">Method name (sort)</param> /// <param name="intList">List with arrays to sort</param> /// <returns>Report log</returns> public static Report RunOneAlgorithm(string classname, string method, List <int[]> intList) { try { GC.Collect(); Logging.WriteLine("################################"); Logging.WriteLine(string.Format("Algorithm: {0}", classname)); Logging.WriteLine(string.Format("Arrays to test: {0}", intList.Count)); Logging.WriteLine("################################"); Type t = Type.GetType(string.Format("eda12131190311906.{0}", classname)); if (t == null) { return(null); } MethodInfo m = t.GetMethod(method, new[] { typeof(int[]) }); Report report = new Report(classname) { XAxisLabel = "Array number of elements", YAxisLabel = "Execution Time (ms)" }; report.PlotTitles.Add("Sort"); report.PlotTitles.Add("Sort-sorted"); Reports.Add(report); int count = 1; foreach (var intA in intList) { var plotLine = new Report.PlotLine(intA.Length.ToString(CultureInfo.InvariantCulture)); report.PlotLines.Add(plotLine); Logging.WriteLine(string.Format("Array nº{0} with {1} elements", count, intA.Length)); var A = (int[])intA.Clone(); report.Comments.Add(""); report.Comments.Add("Array(" + A.Length + ") " + count + ": " + SystemHelper.ArrayToString(A)); Logging.Write("Sorting"); var methodparams = new object[] { A }; if (ApplicationSettings.Instance.ComputeAverageValueWith <= 1) { var profiler = plotLine.AddProfiler(); m.Invoke(null, methodparams); profiler.Stop(); Logging.WriteLine(string.Format(", Sorted after {0}ms", profiler.ElapsedMilliseconds)); } else { Logging.WriteLine(); Logging.WriteLine(string.Format("------Computing Average for {0} executions------", ApplicationSettings.Instance.ComputeAverageValueWith)); var avgList = new List <StopwatchEx>(ApplicationSettings.Instance.ComputeAverageValueWith); for (int i = 0; i < ApplicationSettings.Instance.ComputeAverageValueWith; i++) { Logging.Write(string.Format("{0}: ", i)); A = (int[])intA.Clone(); methodparams = new object[] { A }; StopwatchEx stopwatch = StopwatchEx.StartNew(); m.Invoke(null, methodparams); stopwatch.Stop(); Logging.WriteLine(string.Format("{0}ms", stopwatch.ElapsedMilliseconds)); avgList.Add(stopwatch); } var averageStopWatch = StopwatchEx.ComputeAverage(avgList, ApplicationSettings.Instance .CutLowerHigherAverageValue); plotLine.AddProfiler(averageStopWatch); Logging.WriteLine(string.Format("-----------Computed Average: {0}ms-----------", averageStopWatch.ElapsedMilliseconds)); } Logging.Write("Sorting sorted array"); report.Comments.Add("Sorted array " + count + ": " + SystemHelper.ArrayToString(A)); if (ApplicationSettings.Instance.ComputeAverageValueWith <= 1) { var profiler1 = plotLine.AddProfiler(); m.Invoke(null, methodparams); profiler1.Stop(); Logging.WriteLine(string.Format(", Sorted after {0}ms", profiler1.ElapsedMilliseconds)); } else { Logging.WriteLine(); Logging.WriteLine(string.Format("------Computing Average for {0} executions------", ApplicationSettings.Instance.ComputeAverageValueWith)); var avgList = new List <StopwatchEx>(ApplicationSettings.Instance.ComputeAverageValueWith); for (int i = 0; i < ApplicationSettings.Instance.ComputeAverageValueWith; i++) { Logging.Write(string.Format("{0}: ", i)); StopwatchEx stopwatch = StopwatchEx.StartNew(); m.Invoke(null, methodparams); stopwatch.Stop(); Logging.WriteLine(string.Format("{0}ms", stopwatch.ElapsedMilliseconds)); avgList.Add(stopwatch); } var averageStopWatch = StopwatchEx.ComputeAverage(avgList, ApplicationSettings.Instance .CutLowerHigherAverageValue); Logging.WriteLine(string.Format("-----------Computed Average: {0}ms-----------", averageStopWatch.ElapsedMilliseconds)); plotLine.AddProfiler(averageStopWatch); } report.Comments.Add("Sorted-sorted array " + count + ": " + SystemHelper.ArrayToString(A)); count++; } Logging.WriteLine("################################"); Logging.WriteLine(string.Format("End of {0} algorithmn", classname)); Logging.WriteLine("################################"); report.WriteToFile(); return(report); } catch (ThreadAbortException) { } catch (Exception e) { MessageBox.Show("Error: " + e.Message); } return(null); }
/// <summary> /// Triggered when background worker start the tasks /// </summary> /// <param name="sender">Object who trigger event</param> /// <param name="e">>Event arguments</param> private void BgWorkerDoWork(object sender, DoWorkEventArgs e) { try { var reports = new List <Report>(); bgWorker.ReportProgress(1, "Generating arrays"); var testArray = new List <int[]>(ApplicationSettings.Instance.NumberOfTests); double size = ApplicationSettings.Instance.ArrayInitialSize; int minvalue = Math.Max(100, Convert.ToInt32(ApplicationSettings.Instance.ArrayMinRandomNumber)); double maxvalue = ApplicationSettings.Instance.ArrayRandomBetweenValues ? Math.Min(Convert.ToInt32(ApplicationSettings.Instance.ArrayMaxRandomNumber), int.MaxValue) : minvalue; for (int i = 1; i <= ApplicationSettings.Instance.NumberOfTests; i++) { if (size <= 0) { size = i * 10; } testArray.Add(SystemHelper.RandomIntegerArray(Convert.ToInt32(size), minvalue, Convert.ToInt32(maxvalue))); if (ApplicationSettings.Instance.ArrayGrowFactorType == '+') { size += ApplicationSettings.Instance.ArrayGrowFactor; } else { size *= ApplicationSettings.Instance.ArrayGrowFactor; } if (!ApplicationSettings.Instance.ArrayRandomBetweenValues) { if (ApplicationSettings.Instance.ArrayNumberGrowFactorType == '+') { maxvalue += ApplicationSettings.Instance.ArrayNumberGrowFactor; } else { maxvalue *= ApplicationSettings.Instance.ArrayNumberGrowFactor; } } } var testArrayCopy = SystemHelper.CloneListIntArray(testArray); for (int i = 0; i < cblAlgorithms.CheckedItems.Count; i++) { if (bgWorker.CancellationPending) { return; } while (btnPause.Text.Equals("Resume")) { Thread.Sleep(1000); } string name = cblAlgorithms.CheckedItems[i].ToString(); bgWorker.ReportProgress(i * 100 / cblAlgorithms.CheckedItems.Count + 2, string.Format("Executing {0}/{1} {2}", (i + 1), cblAlgorithms.CheckedItems.Count, name)); Report report = Program.RunOneAlgorithm(name, testArrayCopy); reports.Add(report); testArrayCopy = SystemHelper.CloneListIntArray(testArray); } Report masterReport = Report.BuildMaster(reports); masterReport.WriteToFile(); } catch (ThreadAbortException) { } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Triggerd when any button get clicked /// </summary> /// <param name="sender">Object who trigger event</param> /// <param name="e">Event arguments</param> private void ButtonClick(object sender, EventArgs e) { if (sender == btnAlgorithmsSelectAll) { for (int i = 0; i < cblAlgorithms.Items.Count; i++) { cblAlgorithms.SetItemChecked(i, true); } return; } if (sender == btnAlgorithmsDeselectAll) { for (int i = 0; i < cblAlgorithms.Items.Count; i++) { cblAlgorithms.SetItemChecked(i, false); } return; } if (sender == btnAlgorithmsInvert) { for (int i = 0; i < cblAlgorithms.Items.Count; i++) { cblAlgorithms.SetItemChecked(i, !cblAlgorithms.GetItemChecked(i)); } return; } if (sender == btnViewLog) { if (bgWorker.IsBusy) { return; } cblAlgorithms.Visible = !cblAlgorithms.Visible; btnViewLog.Text = cblAlgorithms.Visible ? "View &Log" : "Hide &Log"; } if (sender == btnSearchGnuplotExe) { using (var openDialog = new OpenFileDialog()) { string workingDir = SystemHelper.IsWindows() ? Path.GetDirectoryName(ApplicationSettings.Instance.GnuplotFullPath) : (ApplicationSettings.Instance.GnuplotFullPath.Equals("gnuplot") ? "/usr/bin" : Path.GetDirectoryName(ApplicationSettings.Instance.GnuplotFullPath)); openDialog.CheckFileExists = true; openDialog.AddExtension = false; openDialog.CheckPathExists = true; openDialog.RestoreDirectory = true; openDialog.InitialDirectory = workingDir; openDialog.FileName = (SystemHelper.IsWindows() ? "wgnuplot.exe" : "gnuplot"); openDialog.Filter = SystemHelper.IsWindows() ? "Gnuplot windows executable (wgnuplot.exe)|wgnuplot.exe" : "Gnuplot executable (gnuplot*)|gnuplot*"; if (openDialog.ShowDialog() == DialogResult.OK) { ApplicationSettings.Instance.GnuplotFullPath = tbGnuplotExecutable.Text = openDialog.FileName; } } return; } if (sender == btnSaveReportsTo) { using (var folderDialog = new FolderBrowserDialog()) { folderDialog.Description = @"Folder to save all reports and algorithm work"; folderDialog.SelectedPath = Application.StartupPath; if (folderDialog.ShowDialog() == DialogResult.OK) { // Absolute to partial path convertion string path = folderDialog.SelectedPath.Replace(Application.StartupPath, string.Empty); if (!string.IsNullOrEmpty(path) && path.Substring(0, 1) == Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture)) { path = path.Remove(0, 1); } ApplicationSettings.Instance.ReportsPath = tbSaveReportsTo.Text = path; } } return; } if (sender == cbAutoOpenPlots) { ApplicationSettings.Instance.AutoOpenPlot = cbAutoOpenPlots.Checked; return; } if (sender == cbArrayRandomBetweenValues) { ApplicationSettings.Instance.ArrayRandomBetweenValues = cbArrayRandomBetweenValues.Checked; nmArrayMaxRandomNumber.Enabled = cbArrayRandomBetweenValues.Checked; nmArrayNumberGrowFactor.Enabled = !cbArrayRandomBetweenValues.Checked; return; } if (sender == btnStart) { if (bgWorker.IsBusy) { return; } ApplicationSettings.Save(); Report.GenerateGnuplotFiles(); gbOptions.Enabled = false; btnStart.Enabled = false; btnStop.Enabled = btnPause.Enabled = true; pbLoad.Value = 0; pbLoad.Text = @"Starting"; Program.Logging.Clear(); tsAlgortimsBar.Enabled = cblAlgorithms.Visible = false; Stopwatcher.Reset(); Stopwatcher.Start(); tmClock.Start(); bgWorker.RunWorkerAsync(); return; } if (sender == btnPause) { btnPause.Text = btnPause.Text.Equals("Pause") ? "Resume" : "Pause"; return; } if (sender == btnStop) { if (bgWorker.CancellationPending) { return; } if ( MessageBox.Show("Have you sure you want stop current work?\nAfter stop there are no backwards", @"Cancellation", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) != DialogResult.Yes) { return; } bgWorker.AbortCancel(); btnPause.Enabled = btnStop.Enabled = false; btnPause.Text = "Pause"; lbStatus.Text += @" -> Cancel Requested -> Waiting for finish"; } }