Click here to Skip to main content
15,891,938 members
Articles / Desktop Programming / WPF
Tip/Trick

C# Code Execution Time Compiler - WPF Application

Rate me:
Please Sign up or sign in to vote.
1.80/5 (4 votes)
15 Aug 2015CPOL1 min read 12K   3   4
A Windows application which processes your code and shows how much time it takes to execute your code.

Introduction

This is a Windows application which processes your code and shows how much time it takes to execute your code.

Using the Code

The application image is shown below:

<a href="http://ptcSuccess.png" target="_self"><img alt="" src="/KB/dotnet/1019082/ptcSuccess.png" style="width: 640px; height: 342px;" /></a>

You should append your code at "//Enter your code here..." section. Once you complete your code editing, click on run button, then you can see how much time your code takes for execution at the bottom(output) tab.

If your code had any errors, then all the error messages will be displayed in the output tab.

Image 1

Once we look at the code, we can see how exactly our application works.

C#
using System;
using System.Windows;
using System.Windows.Documents;
using RTenney.Utility.Timekeeping;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Windows.Controls;
using System.Windows.Media;

namespace ProcessingTimeCalculator
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            codeTextAreaRak.AppendText(GetInitialCodeTemplate());
        }

        public string GetInitialCodeTemplate()
        {
            string code =
                @"using System;
                  namespace RV
                     {
                       public class RvApps
                             {
                                public static void Main()
                                   {
                                       //Enter your code here...
                                    }
                              }
                      }
                ";
            return code;
        }

        private void runBtn_Click(object sender, RoutedEventArgs e)
        {
            codeTextAreaRak.IsReadOnly = true;
            string code = new TextRange
            (codeTextAreaRak.Document.ContentStart, codeTextAreaRak.Document.ContentEnd).Text;
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();
            // Reference to System.Drawing library
            parameters.ReferencedAssemblies.Add("System.Drawing.dll");
            // True - memory generation, false - external file generation
            parameters.GenerateInMemory = true;
            // True - exe file generation, false - dll file generation
            parameters.GenerateExecutable = true;
            CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
            if (results.Errors.HasErrors)
            {
                OutputWindow.Foreground = Brushes.Red;
                foreach (CompilerError error in results.Errors)
                {
                    OutputWindow.AppendText
                    (String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
                    OutputWindow.AppendText("\n");
                }
                codeTextAreaRak.IsReadOnly = false;
                return;
            }
            OutputWindow.Foreground = Brushes.Green;
            Assembly assembly = results.CompiledAssembly;
            Type program = assembly.GetType("RV.RvApps");
            MethodInfo main = program.GetMethod("Main");
            TimeData timer = Timekeeper.StartNew();
            main.Invoke(null, null);
            Timekeeper.End(timer);
            double timeCount = timer.Time;
            OutputWindow.AppendText
            (DateTime.Now+": Total time of execution " + timeCount+"\n");
            codeTextAreaRak.IsReadOnly = false;
        }
    }
}

CodeTextRak and OutputWindow are rich textbox controls. Your code will be appended to CodeTextRak rich text box and output will be displayed in OutputWindow rich textbox.

C#
public MainWindow()
        {
            InitializeComponent();
            codeTextAreaRak.AppendText(GetInitialCodeTemplate());
        }

Here CodeTextAreaRak section will be loaded with initial template and all other controls will be initialized.

C#
private void runBtn_Click(object sender, RoutedEventArgs e)
       {
           codeTextAreaRak.IsReadOnly = true;//While we are processing
                   // your code we are making it non editable
           string code = new TextRange(codeTextAreaRak.Document.ContentStart,
           codeTextAreaRak.Document.ContentEnd).Text; // We are saving all your code into a string
           CSharpCodeProvider provider = new CSharpCodeProvider();
           CompilerParameters parameters = new CompilerParameters();
           // Reference to System.Drawing library
           parameters.ReferencedAssemblies.Add("System.Drawing.dll");
           // True - memory generation, false - external file generation
           parameters.GenerateInMemory = true;
           // True - exe file generation, false - dll file generation
           parameters.GenerateExecutable = true;
           CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
           if (results.Errors.HasErrors)
           {
               OutputWindow.Foreground =
               Brushes.Red;//for error messages we are changing font color to red.
               foreach (CompilerError error in results.Errors)
               {
                   OutputWindow.AppendText(String.Format("Error ({0}): {1}",
                   error.ErrorNumber, error.ErrorText)); //we are copying all errors to OutputWindow
                   OutputWindow.AppendText("\n");// creating a new line after each error.
               }
               codeTextAreaRak.IsReadOnly = false; // after completion of processing
                           // we are making codetextarea to be editable by user.
               return;
           }
           OutputWindow.Foreground =
           Brushes.Green;// for successful outputs we are making foreground color as green.
           Assembly assembly = results.CompiledAssembly;//getting compiled assembly
           Type program = assembly.GetType("RV.RvApps");//tracking your code area.
           MethodInfo main = program.GetMethod("Main");//calling Main method of your code.
           TimeData timer = Timekeeper.StartNew();//starting timer
           main.Invoke(null, null);//invoking main method
           Timekeeper.End(timer);// stopping timer
           double timeCount = timer.Time;//getting calculated time
           OutputWindow.AppendText(DateTime.Now+": Total time of execution " +
           timeCount+"\n");//showing calculated time in output window.
           codeTextAreaRak.IsReadOnly = false;
       }

How each line of the code works is clearly explained as a comment next to it.

Points of Interest

Usually, I like to write my code in online compiler sites like codechef, techgig, google codejam. While writing code, I always think of how exactly these sites compile our code and sometimes I think of doing an offline version of it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralGreate Pin
Aladár Horváth16-Aug-15 22:13
professionalAladár Horváth16-Aug-15 22:13 
Thanks
QuestionThis was a tip... Pin
OriginalGriff15-Aug-15 21:50
mveOriginalGriff15-Aug-15 21:50 
AnswerRe: This was a tip... Pin
Nelek15-Aug-15 23:35
protectorNelek15-Aug-15 23:35 
QuestionWhy not roslyn Pin
Sacha Barber15-Aug-15 21:17
Sacha Barber15-Aug-15 21:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.