Skip to content

Instantly share code, notes, and snippets.

@bwedding
Last active August 18, 2019 01:24
Show Gist options
  • Save bwedding/55d038043f963bd87a8da94b31ddfe1f to your computer and use it in GitHub Desktop.
Save bwedding/55d038043f963bd87a8da94b31ddfe1f to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.Text;
namespace CSharpBenchmark
{
class Program
{
private static Random random = new Random();
// Generate a random string with a given size
// and place commas about every 12th position.
// Note: This function is not optimized as its
// not including in the benchmark timing
public static string RandomString(int size)
{
var buf = new byte[size];
byte ch;
int commaLocation = 0;
bool PlaceComma = false;
for (int i = 0; i < size; i++)
{
// If we're at the 12th char, get
// a random number from 0-4 as a place
// to stick a comma instead of
// a character
if(i != 0 && i % 12 == 0)
{
commaLocation = random.Next(0, 4) + i;
PlaceComma = true;
}
// Get a random ASCII character
// and stick it in the byte array unless
// its time to add a comma
ch = Convert.ToByte(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
if(PlaceComma && i == commaLocation)
{
buf[i] = Convert.ToByte(',');
PlaceComma = false;
}
else
{
buf[i] = ch;
}
}
// return a string
return Encoding.UTF8.GetString(buf, 0, buf.Length);
}
// For every comma in the string, replace
// it with a comma and linefeed
public static string AddLineFeeds(string text)
{
StringBuilder sb = new StringBuilder(text);
sb.Replace(",", ",\n");
return sb.ToString();
}
static void Main(string[] args)
{
Stopwatch stopWatch = new Stopwatch();
string final = "";
// We'll benchmark with 100 different random strings
// Creation of the string is not counted in the timing
for (int i = 0; i < 100; i++)
{
// Size of the string will be between 4Mb and 8Mb
int Len = 4000000 + random.Next(0, 4000000);
var buffer = RandomString(Len);
Console.SetCursorPosition(0, 0);
Console.WriteLine("Run # {0}", i+1);
// For each string, add the linefeeds to it
// Do this 10 times
stopWatch.Start();
for (int j = 0; j < 10; j++)
{
final = AddLineFeeds(buffer);
}
stopWatch.Stop();
}
// Print the final benchmark results
TimeSpan ts = stopWatch.Elapsed;
PrintBenchmark(ts);
}
// Format and display the TimeSpan value.
private static void PrintBenchmark(TimeSpan ts)
{
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment