aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.Profiler/InternalProfile.cs
blob: 46984601b5e828b0a49420c7639568ed5229bc15 (plain) (blame)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Ryujinx.Common;

namespace Ryujinx.Profiler
{
    public class InternalProfile
    {
        private struct TimerQueueValue
        {
            public ProfileConfig Config;
            public long Time;
            public bool IsBegin;
        }

        internal Dictionary<ProfileConfig, TimingInfo> Timers { get; set; }

        private readonly object _timerQueueClearLock = new object();
        private ConcurrentQueue<TimerQueueValue> _timerQueue;

        private int _sessionCounter = 0;

        // Cleanup thread
        private readonly Thread _cleanupThread;
        private bool _cleanupRunning;
        private readonly long _history;
        private long _preserve;

        // Timing flags
        private TimingFlag[] _timingFlags;
        private long[] _timingFlagAverages;
        private long[] _timingFlagLast;
        private long[] _timingFlagLastDelta;
        private int _timingFlagCount;
        private int _timingFlagIndex;

        private int _maxFlags;

        private Action<TimingFlag> _timingFlagCallback;

        public InternalProfile(long history, int maxFlags)
        {
            _maxFlags            = maxFlags;
            Timers               = new Dictionary<ProfileConfig, TimingInfo>();
            _timingFlags         = new TimingFlag[_maxFlags];
            _timingFlagAverages  = new long[(int)TimingFlagType.Count];
            _timingFlagLast      = new long[(int)TimingFlagType.Count];
            _timingFlagLastDelta = new long[(int)TimingFlagType.Count];
            _timerQueue          = new ConcurrentQueue<TimerQueueValue>();
            _history             = history;
            _cleanupRunning      = true;

            // Create cleanup thread.
            _cleanupThread = new Thread(CleanupLoop);
            _cleanupThread.Start();
        }

        private void CleanupLoop()
        {
            bool queueCleared = false;

            while (_cleanupRunning)
            {
                // Ensure we only ever have 1 instance modifying timers or timerQueue
                if (Monitor.TryEnter(_timerQueueClearLock))
                {
                    queueCleared = ClearTimerQueue();

                    // Calculate before foreach to mitigate redundant calculations
                    long cleanupBefore = PerformanceCounter.ElapsedTicks - _history;
                    long preserveStart = _preserve - _history;

                    // Each cleanup is self contained so run in parallel for maximum efficiency
                    Parallel.ForEach(Timers, (t) => t.Value.Cleanup(cleanupBefore, preserveStart, _preserve));

                    Monitor.Exit(_timerQueueClearLock);
                }

                // Only sleep if queue was successfully cleared
                if (queueCleared)
                {
                    Thread.Sleep(5);
                }
            }
        }

        private bool ClearTimerQueue()
        {
            int count = 0;

            while (_timerQueue.TryDequeue(out TimerQueueValue item))
            {
                if (!Timers.TryGetValue(item.Config, out TimingInfo value))
                {
                    value = new TimingInfo();
                    Timers.Add(item.Config, value);
                }

                if (item.IsBegin)
                {
                    value.Begin(item.Time);
                }
                else
                {
                    value.End(item.Time);
                }

                // Don't block for too long as memory disposal is blocked while this function runs
                if (count++ > 10000)
                {
                    return false;
                }
            }

            return true;
        }

        public void FlagTime(TimingFlagType flagType)
        {
            int flagId = (int)flagType;

            _timingFlags[_timingFlagIndex] = new TimingFlag()
            {
                FlagType  = flagType,
                Timestamp = PerformanceCounter.ElapsedTicks
            };

            _timingFlagCount = Math.Max(_timingFlagCount + 1, _maxFlags);

            // Work out average
            if (_timingFlagLast[flagId] != 0)
            {
                _timingFlagLastDelta[flagId] = _timingFlags[_timingFlagIndex].Timestamp - _timingFlagLast[flagId];
                _timingFlagAverages[flagId]  = (_timingFlagAverages[flagId] == 0) ? _timingFlagLastDelta[flagId] :
                                                                                   (_timingFlagLastDelta[flagId] + _timingFlagAverages[flagId]) >> 1;
            }
            _timingFlagLast[flagId] = _timingFlags[_timingFlagIndex].Timestamp;

            // Notify subscribers
            _timingFlagCallback?.Invoke(_timingFlags[_timingFlagIndex]);

            if (++_timingFlagIndex >= _maxFlags)
            {
                _timingFlagIndex = 0;
            }
        }

        public void BeginProfile(ProfileConfig config)
        {
            _timerQueue.Enqueue(new TimerQueueValue()
            {
                Config  = config,
                IsBegin = true,
                Time    = PerformanceCounter.ElapsedTicks,
            });
        }

        public void EndProfile(ProfileConfig config)
        {
            _timerQueue.Enqueue(new TimerQueueValue()
            {
                Config  = config,
                IsBegin = false,
                Time    = PerformanceCounter.ElapsedTicks,
            });
        }

        public string GetSession()
        {
            // Can be called from multiple threads so we need to ensure no duplicate sessions are generated
            return Interlocked.Increment(ref _sessionCounter).ToString();
        }

        public List<KeyValuePair<ProfileConfig, TimingInfo>> GetProfilingData()
        {
            _preserve = PerformanceCounter.ElapsedTicks;

            lock (_timerQueueClearLock)
            {
                ClearTimerQueue();
                return Timers.ToList();
            }
        }

        public TimingFlag[] GetTimingFlags()
        {
            int count = Math.Max(_timingFlagCount, _maxFlags);
            TimingFlag[] outFlags = new TimingFlag[count];
            
            for (int i = 0, sourceIndex = _timingFlagIndex; i < count; i++, sourceIndex++)
            {
                if (sourceIndex >= _maxFlags)
                    sourceIndex = 0;
                outFlags[i] = _timingFlags[sourceIndex];
            }

            return outFlags;
        }

        public (long[], long[]) GetTimingAveragesAndLast()
        {
            return (_timingFlagAverages, _timingFlagLastDelta);
        }

        public void RegisterFlagReceiver(Action<TimingFlag> receiver)
        {
            _timingFlagCallback = receiver;
        }

        public void Dispose()
        {
            _cleanupRunning = false;
            _cleanupThread.Join();
        }
    }
}