Last active
August 29, 2015 13:57
-
-
Save kashwaa/9439639 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Diagnostics; | |
using System.Threading.Tasks; | |
namespace sqr | |
{ | |
class result | |
{ | |
public int i { get; set; } | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Stopwatch sw = new Stopwatch(); | |
int res = 0; | |
result r = new result(); | |
int x = 10000000; | |
Console.WriteLine("result for parallel for with local thread sum and lock:"); | |
sw.Start(); | |
Parallel.For(1, x + 1, () => 0, | |
(i, state, localsum) => { if (sqrchan89(i))localsum++; return localsum; }, | |
(localsum) => { lock (r) r.i += localsum; }); | |
sw.Stop(); | |
Console.WriteLine(r.i); | |
Console.WriteLine(sw.Elapsed); | |
Console.WriteLine("--------------------------"); | |
Console.WriteLine("result for parallel for with local thread sum and Interlocked.Add:"); | |
sw.Restart(); | |
Parallel.For(1, x + 1, () => 0, | |
(i, state, localsum) => { if (sqrchan89(i))localsum++; return localsum; }, | |
(localsum) => { System.Threading.Interlocked.Add(ref res, localsum); }); | |
sw.Stop(); | |
Console.WriteLine(res); | |
Console.WriteLine(sw.Elapsed); | |
Console.WriteLine("--------------------------"); | |
res = 0; | |
Console.WriteLine("result for parallel for with Interlocked.Add:"); | |
Parallel.For(1, x + 1, c => { if (sqrchan89(c))System.Threading.Interlocked.Add(ref res, 1); }); | |
sw.Stop(); | |
Console.WriteLine(res); | |
Console.WriteLine(sw.Elapsed); | |
Console.ReadLine(); | |
} | |
public static int sqrSum(int number) | |
{ | |
int res = 0; | |
while (number > 0) | |
{ | |
int x = number % 10; | |
res += (int)Math.Pow(x, 2); | |
number /= 10; | |
} | |
return res; | |
} | |
static bool sqrchan89(int number) | |
{ | |
if (number == 89) return true; | |
else if (number == 1) return false; | |
else return sqrchan89(sqrSum(number)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment