summaryrefslogtreecommitdiff
path: root/indra/llcommon/lltraceaccumulators.h
blob: 7267a44300cd605eef702d68b2f5c04e76d718b4 (plain)
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615

/** 
 * @file lltraceaccumulators.h
 * @brief Storage for accumulating statistics
 *
 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2012, Linden Research, Inc.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#ifndef LL_LLTRACEACCUMULATORS_H
#define LL_LLTRACEACCUMULATORS_H


#include "stdtypes.h"
#include "llpreprocessor.h"
#include "llunits.h"
#include "lltimer.h"
#include "llrefcount.h"
#include "llthreadlocalstorage.h"
#include "llmemory.h"
#include <limits>

namespace LLTrace
{
	const F64 NaN	= std::numeric_limits<double>::quiet_NaN();

	enum EBufferAppendType
	{
		SEQUENTIAL,
		NON_SEQUENTIAL
	};

	template<typename ACCUMULATOR>
	class AccumulatorBuffer : public LLRefCount
	{
		typedef AccumulatorBuffer<ACCUMULATOR> self_t;
		static const S32 DEFAULT_ACCUMULATOR_BUFFER_SIZE = 32;
	private:
		struct StaticAllocationMarker { };

		AccumulatorBuffer(StaticAllocationMarker m)
		:	mStorageSize(0),
			mStorage(NULL)
		{}

	public:
		AccumulatorBuffer()
			: mStorageSize(0),
			mStorage(NULL)
		{
            LL_PROFILE_ZONE_SCOPED_CATEGORY_STATS;
			const AccumulatorBuffer& other = *getDefaultBuffer();
			resize(sNextStorageSlot);
			for (S32 i = 0; i < sNextStorageSlot; i++)
			{
				mStorage[i] = other.mStorage[i];
			}
		}

		~AccumulatorBuffer()
		{
            LL_PROFILE_ZONE_SCOPED_CATEGORY_STATS;
			if (isCurrent())
			{
				LLThreadLocalSingletonPointer<ACCUMULATOR>::setInstance(NULL);
			}
			delete[] mStorage;
		}

		LL_FORCE_INLINE ACCUMULATOR& operator[](size_t index) 
		{ 
			return mStorage[index]; 
		}

		LL_FORCE_INLINE const ACCUMULATOR& operator[](size_t index) const
		{ 
			return mStorage[index]; 
		}


		AccumulatorBuffer(const AccumulatorBuffer& other)
			: mStorageSize(0),
			mStorage(NULL)
		{
            LL_PROFILE_ZONE_SCOPED_CATEGORY_STATS;
			resize(sNextStorageSlot);
			for (S32 i = 0; i < sNextStorageSlot; i++)
			{
				mStorage[i] = other.mStorage[i];
			}
		}

		void addSamples(const AccumulatorBuffer<ACCUMULATOR>& other, EBufferAppendType append_type)
		{
            LL_PROFILE_ZONE_SCOPED_CATEGORY_STATS;
			llassert(mStorageSize >= sNextStorageSlot && other.mStorageSize >= sNextStorageSlot);
			for (size_t i = 0; i < sNextStorageSlot; i++)
			{
				mStorage[i].addSamples(other.mStorage[i], append_type);
			}
		}

		void copyFrom(const AccumulatorBuffer<ACCUMULATOR>& other)
		{
            LL_PROFILE_ZONE_SCOPED_CATEGORY_STATS;
			llassert(mStorageSize >= sNextStorageSlot && other.mStorageSize >= sNextStorageSlot);
			for (size_t i = 0; i < sNextStorageSlot; i++)
			{
				mStorage[i] = other.mStorage[i];
			}
		}

		void reset(const AccumulatorBuffer<ACCUMULATOR>* other = NULL)
		{
            LL_PROFILE_ZONE_SCOPED_CATEGORY_STATS;
			llassert(mStorageSize >= sNextStorageSlot);
			for (size_t i = 0; i < sNextStorageSlot; i++)
			{
				mStorage[i].reset(other ? &other->mStorage[i] : NULL);
			}
		}

		void sync(F64SecondsImplicit time_stamp)
		{
            LL_PROFILE_ZONE_SCOPED_CATEGORY_STATS;
			llassert(mStorageSize >= sNextStorageSlot);
			for (size_t i = 0; i < sNextStorageSlot; i++)
			{
				mStorage[i].sync(time_stamp);
			}
		}

		void makeCurrent()
		{
			LLThreadLocalSingletonPointer<ACCUMULATOR>::setInstance(mStorage);
		}

		bool isCurrent() const
		{
			return LLThreadLocalSingletonPointer<ACCUMULATOR>::getInstance() == mStorage;
		}

		static void clearCurrent()
		{
            LLThreadLocalSingletonPointer<ACCUMULATOR>::setInstance(NULL);
		}

		// NOTE: this is not thread-safe.  We assume that slots are reserved in the main thread before any child threads are spawned
		size_t reserveSlot()
		{
            LL_PROFILE_ZONE_SCOPED_CATEGORY_STATS;
			size_t next_slot = sNextStorageSlot++;
			if (next_slot >= mStorageSize)
			{
				// don't perform doubling, as this should only happen during startup
				// want to keep a tight bounds as we will have a lot of these buffers
				resize(mStorageSize + mStorageSize / 2);
			}
			llassert(mStorage && next_slot < mStorageSize);
			return next_slot;
		}

		void resize(size_t new_size)
		{
            LL_PROFILE_ZONE_SCOPED_CATEGORY_STATS;
			if (new_size <= mStorageSize) return;

			ACCUMULATOR* old_storage = mStorage;
			mStorage = new ACCUMULATOR[new_size];
			if (old_storage)
			{
				for (S32 i = 0; i < mStorageSize; i++)
				{
					mStorage[i] = old_storage[i];
				}
			}
			mStorageSize = new_size;
			delete[] old_storage;

			self_t* default_buffer = getDefaultBuffer();
			if (this != default_buffer
				&& new_size > default_buffer->size())
			{
				//NB: this is not thread safe, but we assume that all resizing occurs during static initialization
				default_buffer->resize(new_size);
			}
		}

		size_t size() const
		{
			return getNumIndices();
		}

		size_t capacity() const
		{
			return mStorageSize;
		}

		static size_t getNumIndices() 
		{
			return sNextStorageSlot;
		}

		static self_t* getDefaultBuffer()
		{
            LL_PROFILE_ZONE_SCOPED_CATEGORY_STATS;
			static bool sInitialized = false;
			if (!sInitialized)
			{
				// this buffer is allowed to leak so that trace calls from global destructors have somewhere to put their data
				// so as not to trigger an access violation
				sDefaultBuffer = new AccumulatorBuffer(StaticAllocationMarker());
				sInitialized = true;
				sDefaultBuffer->resize(DEFAULT_ACCUMULATOR_BUFFER_SIZE);
			}
			return sDefaultBuffer;
		}

	private:
		ACCUMULATOR*	mStorage;
		size_t			mStorageSize;
		static size_t	sNextStorageSlot;
		static self_t*	sDefaultBuffer;
	};

	template<typename ACCUMULATOR> size_t AccumulatorBuffer<ACCUMULATOR>::sNextStorageSlot = 0;
	template<typename ACCUMULATOR> AccumulatorBuffer<ACCUMULATOR>* AccumulatorBuffer<ACCUMULATOR>::sDefaultBuffer = NULL;

	class EventAccumulator
	{
	public:
		typedef F64 value_t;
		static F64 getDefaultValue() { return NaN; }

		EventAccumulator()
		:	mSum(0),
			mMin(F32(NaN)),
			mMax(F32(NaN)),
			mMean(NaN),
			mSumOfSquares(0),
			mNumSamples(0),
			mLastValue(NaN)
		{}

		void record(F64 value)
		{
			if (mNumSamples == 0)
			{
				mSum = value;
				mMean = value;
				mMin = value;
				mMax = value;
			}
			else
			{
				mSum += value;
				F64 old_mean = mMean;
				mMean += (value - old_mean) / (F64)mNumSamples;
				mSumOfSquares += (value - old_mean) * (value - mMean);

				if (value < mMin) { mMin = value; }
				else if (value > mMax) { mMax = value; }
			}

			mNumSamples++;
			mLastValue = value;
		}

		void addSamples(const EventAccumulator& other, EBufferAppendType append_type);
		void reset(const EventAccumulator* other);
		void sync(F64SecondsImplicit) {}

		F64	getSum() const               { return mSum; }
		F32	getMin() const               { return mMin; }
		F32	getMax() const               { return mMax; }
		F64	getLastValue() const         { return mLastValue; }
		F64	getMean() const              { return mMean; }
		F64 getStandardDeviation() const { return sqrtf(mSumOfSquares / mNumSamples); }
		F64 getSumOfSquares() const		 { return mSumOfSquares; }
		S32 getSampleCount() const       { return mNumSamples; }
		bool hasValue() const			 { return mNumSamples > 0; }

		// helper utility to calculate combined sumofsquares total
		static F64 mergeSumsOfSquares(const EventAccumulator& a, const EventAccumulator& b);

	private:
		F64	mSum,
			mLastValue;

		F64	mMean,
			mSumOfSquares;

		F32 mMin,
			mMax;

		S32	mNumSamples;
	};


	class SampleAccumulator
	{
	public:
		typedef F64 value_t;
		static F64 getDefaultValue() { return NaN; }

		SampleAccumulator()
		:	mSum(0),
			mMin(F32(NaN)),
			mMax(F32(NaN)),
			mMean(NaN),
			mSumOfSquares(0),
			mLastSampleTimeStamp(0),
			mTotalSamplingTime(0),
			mNumSamples(0),
			mLastValue(NaN),
			mHasValue(false)
		{}

		void sample(F64 value)
		{
            LL_PROFILE_ZONE_SCOPED_CATEGORY_STATS;
			F64SecondsImplicit time_stamp = LLTimer::getTotalSeconds();

			// store effect of last value
			sync(time_stamp);

			if (!mHasValue)
			{
				mHasValue = true;

				mMin = value;
				mMax = value;
				mMean = value;
				mLastSampleTimeStamp = time_stamp;
			}
			else
			{
				if (value < mMin) { mMin = value; }
				else if (value > mMax) { mMax = value; }
			}

			mLastValue = value;
			mNumSamples++;
		}

		void addSamples(const SampleAccumulator& other, EBufferAppendType append_type);
		void reset(const SampleAccumulator* other);

		void sync(F64SecondsImplicit time_stamp)
		{
			if (mHasValue && time_stamp != mLastSampleTimeStamp)
			{
				F64SecondsImplicit delta_time = time_stamp - mLastSampleTimeStamp;
				mSum += mLastValue * delta_time;
				mTotalSamplingTime += delta_time;
				F64 old_mean = mMean;
				mMean += (delta_time / mTotalSamplingTime) * (mLastValue - old_mean);
				mSumOfSquares += delta_time * (mLastValue - old_mean) * (mLastValue - mMean);
			}
			mLastSampleTimeStamp = time_stamp;
		}

		F64	getSum() const               { return mSum; }
		F32	getMin() const               { return mMin; }
		F32	getMax() const               { return mMax; }
		F64	getLastValue() const         { return mLastValue; }
		F64	getMean() const              { return mMean; }
		F64 getStandardDeviation() const { return sqrtf(mSumOfSquares / mTotalSamplingTime); }
		F64 getSumOfSquares() const		 { return mSumOfSquares; }
		F64SecondsImplicit getSamplingTime() const { return mTotalSamplingTime; }
		S32 getSampleCount() const       { return mNumSamples; }
		bool hasValue() const            { return mHasValue; }

		// helper utility to calculate combined sumofsquares total
		static F64 mergeSumsOfSquares(const SampleAccumulator& a, const SampleAccumulator& b);

	private:
		F64		mSum,
				mLastValue;

		F64		mMean,
				mSumOfSquares;

		F64SecondsImplicit	
				mLastSampleTimeStamp,
				mTotalSamplingTime;

		F32		mMin,
				mMax;

		S32		mNumSamples;
		// distinct from mNumSamples, since we might have inherited a last value from
		// a previous sampling period
		bool	mHasValue;		
	};

	class CountAccumulator
	{
	public:
		typedef F64 value_t;
		static F64 getDefaultValue() { return 0; }

		CountAccumulator()
		:	mSum(0),
			mNumSamples(0)
		{}

		void add(F64 value)
		{
			mNumSamples++;
			mSum += value;
		}

		void addSamples(const CountAccumulator& other, EBufferAppendType /*type*/)
		{
			mSum += other.mSum;
			mNumSamples += other.mNumSamples;
		}

		void reset(const CountAccumulator* other)
		{
			mNumSamples = 0;
			mSum = 0;
		}

		void sync(F64SecondsImplicit) {}

		F64	getSum() const { return mSum; }

		S32 getSampleCount() const { return mNumSamples; }

		bool hasValue() const			 { return true; }

	private:
		F64	mSum;

		S32	mNumSamples;
	};

	class alignas(32) TimeBlockAccumulator
	{
    public:
		typedef F64Seconds value_t;
		static F64Seconds getDefaultValue() { return F64Seconds(0); }

		typedef TimeBlockAccumulator self_t;

		// fake classes that allows us to view different facets of underlying statistic
		struct CallCountFacet 
		{
			typedef S32 value_t;
		};

		struct SelfTimeFacet
		{
			typedef F64Seconds value_t;
		};

		// arrays are allocated with 32 byte alignment
		void *operator new [](size_t size)
		{
			return ll_aligned_malloc<32>(size);
		}

		void operator delete[](void* ptr, size_t size)
		{
			ll_aligned_free<32>(ptr);
		}

		TimeBlockAccumulator();
		void addSamples(const self_t& other, EBufferAppendType append_type);
		void reset(const self_t* other);
		void sync(F64SecondsImplicit) {}
		bool hasValue() const { return true; }

		//
		// members
		//
		U64							mTotalTimeCounter,
									mSelfTimeCounter;
		S32							mCalls;
		class BlockTimerStatHandle*	mParent;		// last acknowledged parent of this time block
		class BlockTimerStatHandle*	mLastCaller;	// used to bootstrap tree construction
		U16							mActiveCount;	// number of timers with this ID active on stack
		bool						mMoveUpTree;	// needs to be moved up the tree of timers at the end of frame

	};

	class BlockTimerStatHandle;

	class TimeBlockTreeNode
	{
	public:
		TimeBlockTreeNode();

		void setParent(BlockTimerStatHandle* parent);
		BlockTimerStatHandle* getParent() { return mParent; }

		BlockTimerStatHandle*					mBlock;
		BlockTimerStatHandle*					mParent;	
		std::vector<BlockTimerStatHandle*>		mChildren;
		bool						mCollapsed;
		bool						mNeedsSorting;
	};
	
	struct BlockTimerStackRecord
	{
		class BlockTimer*	mActiveTimer;
		class BlockTimerStatHandle*	mTimeBlock;
		U64					mChildTime;
	};

	struct MemAccumulator
	{
		typedef F64Bytes value_t;
		static F64Bytes getDefaultValue() { return F64Bytes(0); }

		typedef MemAccumulator self_t;

		// fake classes that allows us to view different facets of underlying statistic
		struct AllocationFacet 
		{
			typedef F64Bytes value_t;
			static F64Bytes getDefaultValue() { return F64Bytes(0); }
		};

		struct DeallocationFacet 
		{
			typedef F64Bytes value_t;
			static F64Bytes getDefaultValue() { return F64Bytes(0); }
		};

		void addSamples(const MemAccumulator& other, EBufferAppendType append_type)
		{
            LL_PROFILE_ZONE_SCOPED_CATEGORY_STATS;
			mAllocations.addSamples(other.mAllocations, append_type);
			mDeallocations.addSamples(other.mDeallocations, append_type);

			if (append_type == SEQUENTIAL)
			{
				mSize.addSamples(other.mSize, SEQUENTIAL);
			}
			else
			{
				F64 allocation_delta(other.mAllocations.getSum() - other.mDeallocations.getSum());
				mSize.sample(mSize.hasValue() 
					? mSize.getLastValue() + allocation_delta 
					: allocation_delta);
			}
		}

		void reset(const MemAccumulator* other)
		{
            LL_PROFILE_ZONE_SCOPED_CATEGORY_STATS;
			mSize.reset(other ? &other->mSize : NULL);
			mAllocations.reset(other ? &other->mAllocations : NULL);
			mDeallocations.reset(other ? &other->mDeallocations : NULL);
		}

		void sync(F64SecondsImplicit time_stamp) 
		{
			mSize.sync(time_stamp);
		}

		bool hasValue() const			 { return mSize.hasValue(); }

		SampleAccumulator	mSize;
		EventAccumulator	mAllocations;
		CountAccumulator	mDeallocations;
	};

	struct AccumulatorBufferGroup : public LLRefCount
	{
		AccumulatorBufferGroup();
		AccumulatorBufferGroup(const AccumulatorBufferGroup&);
		~AccumulatorBufferGroup();

		void handOffTo(AccumulatorBufferGroup& other);
		void makeCurrent();
		bool isCurrent() const;
		static void clearCurrent();

		void append(const AccumulatorBufferGroup& other);
		void merge(const AccumulatorBufferGroup& other);
		void reset(AccumulatorBufferGroup* other = NULL);
		void sync();

		AccumulatorBuffer<CountAccumulator>	 	mCounts;
		AccumulatorBuffer<SampleAccumulator>	mSamples;
		AccumulatorBuffer<EventAccumulator>		mEvents;
		AccumulatorBuffer<TimeBlockAccumulator> mStackTimers;
		AccumulatorBuffer<MemAccumulator> 	mMemStats;
	};
}

#endif // LL_LLTRACEACCUMULATORS_H