-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathClock.cs
71 lines (59 loc) · 2.42 KB
/
Clock.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System.Diagnostics;
using System.Threading;
using System;
public class Clock
{
public bool QuitRequested;
public delegate void TickHandler();
public event TickHandler Tick;
public float DeltaTime;
public int DeltaTimeMili;
public int LogRate;
public bool Log;
private AutoResetEvent timerEvent = new AutoResetEvent(true);
public Clock(float ticksPerSecond, bool log, int logRate)
{
DeltaTime = 1 / ticksPerSecond;
DeltaTimeMili = (int)(DeltaTime * 1000);
LogRate = logRate;
Log = log;
Thread gameBackgroundThread = new Thread(StartBackgroundloop);
gameBackgroundThread.Priority = ThreadPriority.AboveNormal;
gameBackgroundThread.IsBackground = true;
gameBackgroundThread.Start();
}
public void StartBackgroundloop()
{
double nextTick = DeltaTimeMili;
int count = 0;
double frameStart;
double totalFrameTime = 0;
double maxFrameTime = 0;
Stopwatch timer = Stopwatch.StartNew();
timer.Start();
while (!QuitRequested)
{
frameStart = timer.Elapsed.TotalMilliseconds;
Tick?.Invoke();
totalFrameTime += timer.Elapsed.TotalMilliseconds - frameStart;
maxFrameTime = Math.Max(maxFrameTime, timer.Elapsed.TotalMilliseconds - frameStart);
if (timer.Elapsed.TotalMilliseconds < nextTick)
{
timerEvent.WaitOne((int)(nextTick - timer.Elapsed.TotalMilliseconds));
}
nextTick += DeltaTimeMili;
//framerate displayer
if (Log)
{
count++;
if (count % LogRate == 0)
{
count = 0;
Console.WriteLine("*-----------------------*\n"+timer.Elapsed.TotalMilliseconds.ToString("0.000") + " => Logging performance\n\t"+ totalFrameTime.ToString("0.000") + " => Cumultative delta times since last log\n\t" + maxFrameTime.ToString("0.000") + " => Max delta time since last log"+ "\n*-----------------------*");
totalFrameTime = 0;
maxFrameTime = 0;
}
}
}
}
}