Benchmarking C# Apps & Algorithms

I created a class to help me benchmark my C# algorithms.

Here’s how you can use it:

BenchmarkTimer.Start("Long running algorithm");
for (int x = 0; x < 3; ++x) {
	BenchmarkTimer.Start("Small running algorithm");
	Thread.Sleep(1000);
	BenchmarkTimer.StopAndOutput();
}
BenchmarkTimer.StopAndOutput();

Output:
Small running algorithm: 1000.3712 ms
Small running algorithm: 1000.3712 ms
Small running algorithm: 1000.3712 ms
Long running algorithm: 3001.1136 ms

You can find my entire C# CommonLib library here: http://github.com/jprichardson/CommonLib

Here is the relevant class:

public static class BenchmarkTimer
	{
		private static Stack<BenchmarkData> _startStack = new Stack<BenchmarkData>();

		public static void Start() {
			_startStack.Push(new BenchmarkData());
		}

		public static void Start(string label) {
			var bd = new BenchmarkData() { Label = label };
			_startStack.Push(bd);
		}

		public static TimeSpan Stop() {
			var stop = DateTime.Now;
			var startBD = _startStack.Pop();
			return stop - startBD.DateTime;
		}

		public static void StopAndOutput() {
			var stop = DateTime.Now;
			var startBD = _startStack.Pop();

			var delta = stop - startBD.DateTime;

			var lbl = "{0}: {1} ms";
			Console.WriteLine(String.Format(lbl, startBD.Label, delta.TotalMilliseconds));
		}

		private class BenchmarkData
		{
			public DateTime DateTime { get; set; }
			public string Label { get; set; }

			public BenchmarkData(){
				this.DateTime = DateTime.Now;
				this.Label = "";
			}
		}
	}

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Follow me on Twitter: @jprichardson
Read my blog entrepreneurship: Techneur

-JP

StoryBoard: Animations in WPF

I recently discovered how to do animations in WPF. It’s super simple! So what if you want to create a mouse over animation on a StackPanel? You use the StoryBoard XAML element.
Snippet:

 <Storyboard x:Key="mouseFadeIn">
    <DoubleAnimation  
	Duration="0:0:5"  
	Storyboard.TargetName="myStackPanel"  
	Storyboard.TargetProperty="(UIElement.Opacity)"
	From="0.25"
	To="1.0"/>
</StoryBoard>

This will cause a the Opacity of the element to change from 0.25 to 1.0 over a period of 5 seconds. Note: this should be put in the “Resources” tag. So, if it’s a Window it would be “Window.Resources” or if it’s a UserControl it would be “UserControl.Resources”…
Snippet:

<UserControl.Resources>
  <StoryBoard key="blah">...

So how do we get this to trigger on a mouse over? By using Triggers of course!
Snippet:

<UserControl.Triggers>
	<EventTrigger RoutedEvent="Mouse.MouseEnter" SourceName="myStackPanel">
		<BeginStoryboard Storyboard="{StaticResource mouseFadeIn}" />
	</EventTrigger>
</UserControl.Triggers>

If you want to create a Fade Out effect, just use the “Mouse.MouseLeave” event and reverse the animation. You can even have multiple animations in a StoryBoard. They can run simultaneously or sequentially. If you have multiple animations in a StoryBoard and you want them to run sequentially, you need to add a “BeginTime” attribute. This ensures that the animation is executed after the previous animation(s).

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Follow me on Twitter: @jprichardson

-JP

Traversal of GWT Tree

Recently, an app I’m working on needed two trees. I just so happened that I needed to deep copy part of one of the trees to the other tree. The copied tree will then have checkboxes as nodes instead of just Strings.

So how would you do this? The first solution that came to mine is depth-first traversal of the tree. This method could be adapted to any tree structure in just about any language.

We need a callback function for everytime we ‘hit’ a tree node. Let’s create an interface called ‘Action’:
Action.java:

public interface Action<T> {
	public void execute(T object);
}

Now, we need to create a file called TreeItemUtil.java. This will include the algorithm. The algorithm is really straightforward, it just uses a stack for each node and iterates the stack. If a node has children, they are pushed onto the stack.
TreeItemUtil.java:

public class TreeItemUtil {
	
	public static Collection<TreeItem> fetchChildren(TreeItem ti){
		List<TreeItem> children = new ArrayList<TreeItem>();
		
		for (int i = 0; i < ti.getChildCount(); ++i)
			children.add(ti.getChild(i));
		return children;
	}
	
	public static void traverseDfs(TreeItem root, Action<TreeItem> onNode){
		if (onNode == null)
			throw new IllegalArgumentException("Must pass an action.");
		
		Stack<TreeItem> children = new Stack<TreeItem>();
		children.add(root);
		
		while (!children.isEmpty()){
			TreeItem current = children.pop();
			onNode.execute(current);
			List<TreeItem> currentChildren = fetchChildren(current);
			children.addAll(currentChildren);
		}
	}
}

Here is our TreeItemUtilTest.java that uses Mockito:

public void testTraverseDfs(){
		final StringBuffer sb = new StringBuffer();
		
		TreeItem a = createMockedTI("a");
		TreeItem b = createMockedTI("b");
		TreeItem c = createMockedTI("c");
		TreeItem d = createMockedTI("d");
		TreeItem e = createMockedTI("e");
		TreeItem f = createMockedTI("f");
		TreeItem g = createMockedTI("g");
		TreeItem h = createMockedTI("h");
		TreeItem i = createMockedTI("i");
		TreeItem j = createMockedTI("j");
		TreeItem k = createMockedTI("k");
		TreeItem l = createMockedTI("l");
		TreeItem m = createMockedTI("m");
		TreeItem n = createMockedTI("n");
		TreeItem o = createMockedTI("o");
		TreeItem p = createMockedTI("p");
		
		addMockedChildren(a, b, o);
		addMockedChildren(b, c, i);
		addMockedChildren(o, n, p);
		addMockedChildren(c, d);
		addMockedChildren(i, j, m);
		addMockedChildren(d, e);
		addMockedChildren(j, k, l);
		addMockedChildren(e, f, g);
		addMockedChildren(g, h);
		
		TreeItemUtil.traverseDfs(a, new Action<TreeItem>(){
			public void execute(TreeItem current){
				sb.append(current.getText());
			}
		});
		
		//I was assuming it would be leftmost child first, if so, it would be in alphabetical order
		//but it starts with rightmost node first.
		assertEquals("aopnbimjlkcdeghf", sb.toString());
	}
	
	private TreeItem createMockedTI(String text){
		TreeItem ti = mock(TreeItem.class);
		when(ti.getText()).thenReturn(text);
		return ti;
	}
	
	private void addMockedChildren(TreeItem parent, TreeItem... children){
		for (int x = 0; x < children.length; ++x){
			when(parent.getChild(x)).thenReturn(children[x]);
			when(children[x].getParentItem()).thenReturn(parent);
		}
		
		when(parent.getChildCount()).thenReturn(children.length);
	}

Now for the actual algorithm that clones the TreeItem into a TreeItem with checkboxes:

private TreeItem cloneTreeItemsWithCheckboxes(TreeItem root){
		final HashMap<TreeItem, TreeItem> oldNew = new HashMap<TreeItem, TreeItem>();
		
		TreeItemUtil.traverseDfs(root, new Action<TreeItem>(){
			public void execute(TreeItem current){
				TreeItem newTi = new TreeItem(new CheckBox(current.getText()));
				newTi.setUserObject(current.getUserObject());
				oldNew.put(current, newTi);
				
				if (current.getParentItem() != null && oldNew.containsKey(current.getParentItem())){
					TreeItem newParent = oldNew.get(current.getParentItem());
					newParent.addItem(newTi);
				}
			}
		});
		
		return oldNew.get(root);
	}

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Follow me on Twitter: @jprichardson

-JP

Levenshtein in Ruby 1.9

In Ruby 1.8, I would use the gem ‘levenshtein’… well that doesn’t work in 1.9. So you need to install the gem ‘text’.

Then the call is as simple as:

Text::Levenshtein.distance('hello', 'hell')

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Follow me on Twitter: @jprichardson

-JP

Adding a Close Event When the User Closes the Browser in GWT

Often times your GWT app will queue up client side RPC events. What if the user clicks close on the browser window or tries to navigate to a new page? The solution is very simple.

Window.addWindowClosingHandler(new ClosingHandler(){
	@Override public void onWindowClosing(ClosingEvent event) {
		event.setMessage("If you leave, you may lose data. Continue?");
	}
});

Simple as pie. If event.setMessage is called, a prompt will be displayed for you.

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Follow me on Twitter: @jprichardson

-JP

Hosted WordPress Syntax Highlighting

Dear 2 RSS subscribers:

I’m pleased that you find my snippet blog cool enough to subscribe. I know that you’re use to me posting about once every six months and if you wanted to read my daily writings you would subscribe over at Techneur. But now that I’ve discovered that Hosted WordPress (blogs hosted by wordpress.com) supports syntax highlighting, you’ll probably see a lot more posts. Prepare for the incoming barrage of posts.

Yours truly,

JP

No, but seriously… I didn’t know about this! I’m stoked, I got tired of looking at the crappy background of my code!

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Follow

Get every new post delivered to your Inbox.