Skip to content

Instantly share code, notes, and snippets.

@francisbrito
Last active December 16, 2015 20:48
Show Gist options
  • Save francisbrito/5494783 to your computer and use it in GitHub Desktop.
Save francisbrito/5494783 to your computer and use it in GitHub Desktop.
A simple performance test written in C# using TPL. (Parallel.For)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace PerfTestTpl.ParallelImpl
{
class Program
{
static void Main(string[] args)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
var count = new Stack<int>();
string text;
using (var reader = new StreamReader("./seeds.txt"))
{
text = reader.ReadToEnd();
}
var lines = text.Split('\n');
Parallel.For(0L, lines.Length, (idx) =>
{
var line = lines[idx];
var stringBounds = line.Split(' ');
var bounds = new int[]
{
Convert.ToInt32(stringBounds[0]),
Convert.ToInt32(stringBounds[1])
};
count.Push(PalindromeCountBetween(bounds[0], bounds[1]));
});
Console.WriteLine("Count: {0}", count.Sum());
watch.Stop();
Console.WriteLine("Elapsed: {0} secs", watch.Elapsed.TotalSeconds);
}
public static bool IsPalindrome(int x)
{
var copy = x;
var reverse = 0;
while (copy > 0)
{
reverse = reverse * 10 + copy % 10;
copy /= 10;
}
return x == reverse;
}
public static int PalindromeCountBetween(int lower, int upper)
{
var result = 0;
for (int i = lower; i <= upper; i++)
{
if (IsPalindrome(i))
{
result++;
}
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment