Tuesday, February 27, 2007 3:21 PM
bart
C# Quiz - Need for speed
This quiz was derived from an old piece of code I reviewed for a student's project somewhere in the past. Actually, I was doing some perf-related work today, so I thought it might be useful to have a little quiz around this. Below is the code (reduced in size) of a matrix implementation in C#. Using operator overloads, it supports various operations of which I only kept the multiplication operation (implemented in a very naive way):
using System;
using System.Diagnostics;
class Matrix
{
private double[,] m;
public Matrix(int dim0, int dim1)
{
m = new double[dim0,dim1];
}
public int Height { get { return m.GetLength(0); } }
public int Width { get { return m.GetLength(1); } }
public double this[int x, int y]
{
get { return m[x,y]; }
set { m[x,y] = value; }
}
public static Matrix operator*(Matrix m1, Matrix m2)
{
if (m1.Width != m2.Height)
throw new InvalidOperationException("Matrices should have compatible dimensions for multiplication.");
Matrix m = new Matrix(m1.Height, m2.Width);
for(int i = 0; i < m.Height; i++)
{
for(int j = 0; j < m.Width; j++)
{
m[i,j] = 0;
for (int k = 0; k < m1.Width; k++)
m[i,j] += m1[i,k] * m2[k,j];
}
}
return m;
}
}
class Program
{
static void Main()
{
Random rand = new Random();
Matrix m1 = new Matrix(20,30);
for (int i = 0; i < m1.Height; i++)
for (int j = 0; j < m1.Width; j++)
m1[i,j] = rand.Next(-100,100);
Matrix m2 = new Matrix(30,40);
for (int i = 0; i < m2.Height; i++)
for (int j = 0; j < m2.Width; j++)
m2[i,j] = rand.Next(-100,100);
Matrix r = null;
Stopwatch sw = new Stopwatch();
sw.Start();
for (int k = 0; k < 10000; k++)
r = m1 * m2;
sw.Stop();
Console.WriteLine(sw.Elapsed);
}
}
Feel free to break the loop above at any time if you're satisfied with the result. What's the speed-up factor you can realize? (Tip: You even might want to change something in the process steps 1-3 outlined above to realize a performance boost...) A follow-up post to this quiz question will follow later. Enjoy!