So every now and then you find things that you wish you’d found many years ago. For me, one of those things is the System.Diagnostics.Stopwatch. It is propably one of the simplest objects you can think of, but it saves you a lot of time.

It does what you’d expect: it measures time. And you no longer have to write code to measure time yourself.

In this post I’ll give an example of using the stopwatch to measure the time that it takes to run a heavy method. The fact that the stopwatch knows about that time doesn’t help you: you’ll have to output that time in such a way that you can read it. And you want to be able to do that in a released version of your app, not in – not compiler optimized – debug mode. That’s where Tracing comes in.

The Stopwatch and Tracing are demonstrated in a simple Console Application.

Let’s look at the code!


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;

namespace ReadySetGo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Instantiate a stopwatch
            Stopwatch sw = new Stopwatch();

            // Init the tracing
            // Output to the system tempfolder
            String fileLocation = Path.Combine(Path.GetTempPath(), "MyTraceFile.txt");
            Stream outputFile = File.Create(fileLocation);

            // Setup the tracing
            TextWriterTraceListener textListener = new TextWriterTraceListener(outputFile);
            TraceSource traceSource = new TraceSource("Stopwatch Trace", SourceLevels.All);

            traceSource.Listeners.Clear(); // remove the default ConsoleTraceListener
            traceSource.Listeners.Add(textListener); // add our textlistener

            sw.Start(); // start the stopwatch

            traceSource.TraceEvent(TraceEventType.Verbose, 100, "Invoking DoSomeHeavyWork");
            DoSomeHeavyWork();

            sw.Stop();// stop the stopwatch

            Console.WriteLine("Tracefile written to {0}", fileLocation);

            if (sw.ElapsedMilliseconds > 1000)
            {
                traceSource.TraceEvent(TraceEventType.Warning, 100, "DoSomeHeavyWork took {0} miliseconds", sw.ElapsedMilliseconds.ToString());
            }
            else
            {
                traceSource.TraceEvent(TraceEventType.Verbose, 100, "DoSomeHeavyWork took {0} miliseconds", sw.ElapsedMilliseconds.ToString());
            }
            
            // finish up the traceSource
            traceSource.Flush();
            traceSource.Close();

            // for your convenience: show the tracefile in your default editor
            Process.Start(fileLocation);

            Console.WriteLine("Press a key to exit");
            Console.Read();

        }

        static void DoSomeHeavyWork()
        {
            List lst = new List();
            
            for (int i = 0; i <= 20000; i++)
            {
                if (!lst.Contains(i.ToString())){
                    lst.Add(i.ToString());
                }
            }
        }
    }
}

Let’s analyze this.

First, at line 6 we import the System.Diagnostics. The Stopwatch and Trace functionality are part of it, and so is the Process at line 54.

At line system you find System.IO. Needed because we need a Filestream, and because we use Path to get the default system’s tempdirectory.

Line 17 instantiates a Stopwatch. Easy as pressing a button..

At line 21-22 a stream is created, pointing at a file in the system’s temp directory. This is the file that will contain all tracing information.

Line 25 creates a TextWriterTraceListener. When doing traces, you fire an event at the moment you want to register/trace information. This event can be handled by multiple listeners. In this example we use the TextWriterTraceListener. Everytime an event is fired by the TraceSource, the TextWriterTraceListener catches that and writes the text to the file from the stream we created at line 21. Uhm.. TraceSource?

Line 26 creates the TraceSource. This is the object that will fire the tracing events that are writen to file by the TextWriterTraceListener. We give it the name “Stopwatch Trace”, and tell it to handle all possible trace events.

At line 28 we remove all listeners that are attached to the traceSource. We didn’t add one explicitly, however, when generating a new TraceSource, a default listener is added automatically (one that outputs the trace to the console). We don’t want that, so we remove it. Next, at line 29 we add our TextWriterTraceListener to the TraceSource.

Line 31 starts the stopwatch.

Line 33 tells the TraceSource to fire an event. The type is Verbose. You have multile types, like Critical, Error, Warnig, etc. In this case we just want to tell something, so we make it “verbose”.

You will see the number 100. This is an integer that could have any integer value. the traceSource doesn’t really use it. It only prints this number in your trace file. If you trace multiple processes, you can number those processes. E.g. all calls to webservices get the number 1000, all database transactions get the number 2000, etc. This is just for you, as reference.

Next, at line 34, we invoke a method that takes some time. The method itself contains just some code that consumes time, no other prupose. In real life, this could be a method that does some heavy database queries, or other calculations.

Line 36 stops the stopwatch, after the method has finished.

To read the stopwatch, we use the property ElapsedMilliSeconds.

If the method took more than 1000 milliseconds, the sourceTrace will fire a new event, this time as warning.

If less that 1000 milliseconds, the event will be of type “verbose”.

Note that you can use string formatting in the message (the {} substitutes).

Finally, line 50 and 51 finish the traceSource. This is important, for the traceSource uses a file stream.

Finally, at line 54, the System.Diagnostics.Process.Start method is used to show the trace file, so you do not have to find it in your temp folder yourself.

Run the code, and see what happens. This gives you a tool to find bottlenecks in your code!

Some last remarks.

The tracing is a system that fires events, handels events, and in this case even writes to a file. Note that those things come with performance loss. It’s minimal, but the more you trace, the more resources it’ll take.

If you want to use tracing in a live-application, make sure you build in a way to switch on and off the tracing, e.g. by setting a boolean.

Do Not Panic!

If you are just starting with C# this title may scare you. Well, the terminology did scare me when I just started. However, when you look at it, those <T>’s and I’s are there to make things more easy.

What does it mean? Let’s look at that with an example.

Imagine you build a class called “Dummy”. This class has some properties, e.g. a Name, an Email and an Info (all strings). You have five dummies, and want to store them in a list.

List<T>

That is where you use a generic list. You use the build in List<T&gt, where the T means “just give me a Type, and the list will contain entries of that type only”. Your class Dummy is a Type, so you can make a List of Type Dummy. In syntax: List<Dummy>.

You add your five dumies to that list (as shown in the source code below).

The .Net framework doesn’t know anything about your dummies. Yes, it has a definition, but it does not know the exact meaning of it … in the end the .Net framework exists in a landscape of 0’s and 1’s, if you want something to happen correctly, you’ll have to tell how to do that.

System.InvalidOperationException

Imagine you want to sort your newly created list of dummies. The build-in List (the one that you made a List ) does have a sort method. If you call that method, you’ll get an System.InvalidOperationException. You told the list to sort, but you did not tell it how to do that. Sort on Name, Email, Info? And if you sort on let’s say Info, do you want it to be sorted alphabetical, or maybe some other way? The point is that the list must know how to sort. If only the Dummy class contained some infromation about that…

Interfaces: IComparable<T>

That’s where interfaces come in. If you implement an interface in a class, things like a List still don’t know anything about the meaning of your class, but they do know that there is some functionality in the class they can handle: the information provided by the interface.

When sorting, the List<T> looks for a method that tells how to sort. That method has a signature that is defined in the interface IComparable<T>.

Implementing IComparable<T> in your class means something like: This class has a method that is defined in IComparable. The type that is handled by that method is a generic, in other words, tell me the type, and I’ll respect that type when handling the method!

In our case we want that method to handle a Dummy. So what do we do? In our Dummy Class we implement the interface IComparable of type Dummy. In syntax: IComparable.

If we do so, the List knows how to sort: in your class it looks for the method that belongs to IComparable, and that method is going to tell the List how to sort.

How to sort?

How does that method tell how to sort? Well… it doesn’t by itself, you’ll have to put some code in that method for that. The method looks like this:

public int CompareTo(Dummy other)

As you can see, it returns an int, and it expects a Dummy. This is how it works. When you have an instance of Dummy, that instance also has this method. The method can be called passing another Dummy.

In your code you decide if the other Dummy should be placed before or after the current Dummy when sorting.

If the other Dummy should be placed before the current one, return 1. If the other Dummy should be placed after the current one, return -1.

This gives the List enough information to apply sorting.

Based on what do you return -1 or 1? Well, that’s up to you!

Code Example

In the following code example, a Dummy class is created, the IComparable<T> is implemented, and the sorting will be based on the number of characters in the “Info” property.

Start a new C# WPF project. Call it “Sorter”

In MainWindow.xaml replace the xaml with the following:



<Window x:Class="Sorting.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Sorting"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="17,16,0,0" VerticalAlignment="Top" Height="293" Width="490"/>
    </Grid>
</Window>

In MainWindow.xaml.cs place the following code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Sorting
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        class Dummy : IComparable<Dummy>
        {

            public string Name { get; set; }
            public string Email { get; set; }
            public string Info { get; set; }

            public int CompareTo(Dummy other)
            {
                return (Info.Length > other.Info.Length ? -1 : 1);
             }
        }

        public MainWindow()
        {
            InitializeComponent();

            fillGrid();
        }

        void fillGrid()
        {

            List lst = new List<Dummy>();

            lst.Add(new Dummy() { Name = "Joe", Email = "joe@somedomain.com", Info = "Member of the cocker spaniel club." });
            lst.Add(new Dummy() { Name = "Adrian", Email = "adrian@somedomain.com", Info = "Used to be acrobat" });
            lst.Add(new Dummy() { Name = "Bassie", Email = "bassie@somedomain.com", Info = "His brother used to be a super-hero acrobat, now a days he sells cars." });
            lst.Add(new Dummy() { Name = "Mary", Email = "mary@somedomain.com", Info = "Sweet Mary, I'm coming home!" });
            lst.Add(new Dummy() { Name = "Roger", Email = "roger@somedomain.com", Info = "Likes swimmming in water." });

            lst.Sort();

            dataGrid.ItemsSource = lst;

        }
    }
}

Hopefully, next time you see text with a lot of <T>, capital I’s and Generics, you’ll think: Awesome, someone has spent a lot of time to make my live easier!

This example shows how to read serial data from your Arduino into Processing.

Arduino setup

Connect three photoresistors via a 10K resistor to a 5V power source (you can use your Arduino).
Connect the analog inputs A0, A1 and A2 as in the image below:

Arduino setup

Arduino Setup

Arduino sketch


void setup() { 
  Serial.begin(9600);	
}

void loop() { 
  Serial.write(map(analogRead(A0),0,1023,1,66)); 
  delay(50); 
  Serial.write(map(analogRead(A1),0,1023,67,132)); 
  delay(50); 
  Serial.write(map(analogRead(A2),0,1023,133,199)); 
  delay(50); 
}

Processing Code


/*
Arduino - Read and graph multiple values 
          from Serial Port example
*/

import processing.serial.*;

Serial myPort;

int mWidth=1000;
int mHeight=200; 
int mValue;
int[][] mPoints;

void setup() {

  // set window size and background color 
  size(mWidth, mHeight);

  // init objects/vars
// make sure to replace COM3 with the correct port name:
  myPort = new Serial(this, "COM3", 9600);
  mPoints = new int[mWidth][2];
  for(int i=0;i<Width;i++){ mPoints[i][0]=i; mPoints[i][1]=mHeight; } } void draw() { if ( myPort.available() > 0) {
    background(0); // removes all prior drawn lines

    // draw dividers
    stroke(0,0,120); // dark blue
    line(0,67,mWidth,67);
    line(0,133,mWidth,133);
    stroke(0,255,0); // back to green

    // read the value
    mValue = myPort.read();

    for(int i=0;i<mWidth;i++){ if(i==mWidth-1){ mPoints[i][1] = mHeight-mValue; }else{ mPoints[i][1] = mPoints[i+1][1]; } if(i>3){
        line(mPoints[i-3][0],mPoints[i-3][1],mPoints[i][0],mPoints[i][1]);

      }

    } // next for
  } // end if port available
}

The result is a real-time graph that shows the light intensity:

There are many ways to convert a boolean to text. The most simple one is by using the .ToString() method.

Let’s look at the following code:


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            bool answer;

            answer = (DateTime.Now.Year == 2016);

            
            Console.WriteLine("Yes or no: the current year is 2016?");
            Console.WriteLine("The answer is: {0}", answer.ToString());

            Console.ReadLine();
        }

     }
}

The output will be “The answer is: true” (or false). That’s not what you want, you want the answer to be Yes or No.

You could try something like this:


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            bool answer;

            answer = (DateTime.Now.Year == 2016);

            
            Console.WriteLine("Yes or no: the current year is 2016?");
            Console.WriteLine("The answer is: {0}", answer ? "Yes" : "No");

            Console.ReadLine();
        }
     }
  }

And that works just fine. However, what if you have multiple places where you want to convert a boolean to “Yes” or “No”? You would have to write that code everytime you do the conversion.

And what if you have added this 100 times, and decide afterwards that you do not want “Yes” and “No”, but “Yeah!” and “Nope…”?

For that, the most practical way is using an extention method.

By doing so, you can add functionality to a boolean (and it works on other types as well, in fact, it works on all types!). This is how that’s done:


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            bool answer;
            answer = (DateTime.Now.Year == 2016);
            
            Console.WriteLine("Yes or no: the current year is 2016?");
            Console.WriteLine("The answer is: {0}", answer.ToYesNo());

            Console.ReadLine();
        }
   }

    public static class Extentions
    {
        public static string ToYesNo(this bool b)
        {
            return (b ? "Yes" : "No");
        }
    }
}

All you have to do is add a top-level static class to your project (it can be placed in a separate file, or added to other code, you only need to add it once in your project. The name of that class can be anything, but it makes more sense if you give it a logical name, like “Extentions”.

In that class, you put a public static method, with the return type of your choice (a string in this case). The trick is that you give that method a parameter with the prefix “this“, followed by the type you want to extend (a bool in this case). Give the parameter a name (b).

In the example above, the type bool has a new method: .ToYesNo(). When calling the method, omit the parameter. Simple and effective!

Imagine what you can do with that! Just for fun:


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string sum = "10+10";
            
            Console.WriteLine("The outcome of {0} is {1}",sum, sum.CalcSum());

            Console.ReadLine();
        }
   }

    public static class Extentions
    {
        public static int CalcSum(this string s)
        {
            int ret = 0;
            string[] p = s.Split('+');
            ret = int.Parse(p[0]) + int.Parse(p[1]);

            return ret;
        }
    }
}

EnJoy!

Just some fun code, because I keep on being amazed about how effective, straight forward and especially beautiful Perl can be!


#!/usr/bin/perl -w

use warnings;
use strict;

QUESTION:{

    print 'Type any text, enter "q" to quit: ';
    chomp (my $input = <STDIN>);

    last if ($input eq "q");

    my @arry = split //, $input;
    print "Reversed: ". join("",reverse @arry)."\n";
    redo;
}

print "Bye!\n";