Skip to content

Instantly share code, notes, and snippets.

@mjs3339
Created March 24, 2020 09:20
Show Gist options
  • Save mjs3339/c39b250a5cfb49ae1e4511a3f40c8374 to your computer and use it in GitHub Desktop.
Save mjs3339/c39b250a5cfb49ae1e4511a3f40c8374 to your computer and use it in GitHub Desktop.
CPU Jitter Using Rdtsc
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
[Serializable]
public class JitterEx
{
private const int DesaturationLoopLimit = 50;
private const int UpperCpuLoadLimit = 80;
private const int LowerCpuLoadLimit = 20;
private readonly int _bufferSize;
private readonly object _lock = new object();
private int _loopCount;
private int _tscLoopLimitCpu = 1000;
public Dictionary<int, int> Keep = new Dictionary<int, int>();
public JitterEx(int buffersize)
{
_bufferSize = buffersize;
_loopCount = 0;
}
private void LoadBlock()
{
var DesaturationLoops = 0;
var dump = CpuTotalPc.CPULoad;
do
{
Thread.Sleep(0);
DesaturationLoops++;
} while (DesaturationLoops < DesaturationLoopLimit && ((int) CpuTotalPc.CPULoad > UpperCpuLoadLimit || (int) CpuTotalPc.CPULoad < LowerCpuLoadLimit));
}
[MethodImpl(MethodImplOptions.NoInlining)]
public byte[] GetNextBuffer()
{
var jitterBuffer = new byte[_bufferSize];
var loop = 0;
while (true)
{
var ptr = 0;
var inc = 0;
LoadBlock();
lock (_lock)
{
var start = Rdtsc.TimestampP();
do
{
for (var i = 0; i < _tscLoopLimitCpu; i++)
{
inc++;
inc++;
inc++;
inc++;
}
var stop = Rdtsc.TimestampP();
Buffer.BlockCopy((100000.0 / ((stop - start) * 100000.0)).GetBytes(), 0, jitterBuffer, ptr, 4);
start = stop;
ptr += 4;
} while (ptr < _bufferSize);
if (_loopCount > 3 || loop>=10)
break;
if (ChiSquared.ChiSquaredTest(jitterBuffer).isRandom)
{
if (loop == 0)
_loopCount++;
break;
}
_tscLoopLimitCpu += 1000;
loop++;
Keep.Add(loop, _tscLoopLimitCpu);
}
}
return jitterBuffer;
}
public byte[] GetStackedBuffer(int stackDepth)
{
var firstBuffer = GetNextBuffer();
for (var i = 1; i < stackDepth; ++i)
{
var nextBuffer = i + 1 % 2 == 0 ? GetNextBuffer().Invert() : GetNextBuffer();
for (var j = 0; j < _bufferSize; ++j)
firstBuffer[j] ^= nextBuffer[j];
}
return firstBuffer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment