Last active
February 21, 2020 10:11
-
-
Save ForNeVeR/4216748 to your computer and use it in GitHub Desktop.
False sharing test in C#.
This file contains 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.Diagnostics; | |
using System.Runtime.InteropServices; | |
using System.Threading; | |
namespace ConsoleApplication2 | |
{ | |
class Program | |
{ | |
struct Fuck | |
{ | |
public int x, y; | |
} | |
[StructLayout(LayoutKind.Explicit)] | |
struct Suck | |
{ | |
[FieldOffset(0)] | |
public int x; | |
[FieldOffset(512)] | |
public int y; | |
} | |
private static Fuck fuck; | |
private static Suck suck; | |
static void Main(string[] args) | |
{ | |
var t1 = new Thread(Thread1); | |
var t2 = new Thread(Thread2); | |
var t3 = new Thread(Thread3); | |
var t4 = new Thread(Thread4); | |
var timer = new Stopwatch(); | |
timer.Start(); | |
t1.Start(); | |
t2.Start(); | |
t1.Join(); | |
t2.Join(); | |
timer.Stop(); | |
Console.WriteLine("False sharing: {0} ms", timer.ElapsedMilliseconds); // 617 ms | |
timer = new Stopwatch(); | |
timer.Start(); | |
t3.Start(); | |
t4.Start(); | |
t3.Join(); | |
t4.Join(); | |
timer.Stop(); | |
Console.WriteLine("No false sharing: {0} ms", timer.ElapsedMilliseconds); // 393 ms | |
} | |
private static void Thread1() | |
{ | |
for (int i = 0; i < 100000000; ++i) | |
{ | |
++fuck.x; | |
} | |
} | |
private static void Thread2() | |
{ | |
for (int i = 0; i < 100000000; ++i) | |
{ | |
++fuck.y; | |
} | |
} | |
private static void Thread3() | |
{ | |
for (int i = 0; i < 100000000; ++i) | |
{ | |
++suck.x; | |
} | |
} | |
private static void Thread4() | |
{ | |
for (int i = 0; i < 100000000; ++i) | |
{ | |
++suck.y; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment