GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
profiling.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_CORE_PROFILING_HPP
5#define GREM_CORE_PROFILING_HPP
6
8
10
11#ifdef GREM_USE_PROFILING
12#include <GREM/core/Error.hpp>
33#include <GREM/core/time.hpp>
34
35#include <cstring> // std::strcpy
36#include <source_location> // IWYU pragma: keep // std::source_location
37#include <utility> // std::move
38
39#ifdef GREM_USE_MULTITHREADING
41#ifdef __linux__
42#include <cerrno> // ERANGE
43#include <pthread.h> // pthread_t, pthread_self, pthread_setname_np
44#endif
45#endif
46#endif
47
48namespace grem {
49
53enum class ProfileFormat : uint8_t {
54 BINARY = 1 << 0,
55 JSON = 1 << 1,
57};
58
63public:
67 static const ProfileFormats ALL;
68
72 constexpr ProfileFormats() noexcept = default;
73
82 constexpr ProfileFormats(ProfileFormat format) noexcept
83 : bits(static_cast<uint8_t>(format)) {}
84
92 [[nodiscard]] constexpr bool operator==(const ProfileFormats& other) const noexcept = default;
93
99 [[nodiscard]] constexpr bool empty() const noexcept {
100 return bits == 0;
101 }
102
110 [[nodiscard]] constexpr bool contains(ProfileFormat format) const noexcept {
111 return (bits & ProfileFormats{format}.bits) != 0;
112 }
113
122 [[nodiscard]] constexpr bool containsAnyOf(ProfileFormats formats) const noexcept {
123 return (bits & formats.bits) != 0;
124 }
125
134 [[nodiscard]] constexpr bool containsAllOf(ProfileFormats formats) const noexcept {
135 return (bits & formats.bits) == formats.bits;
136 }
137
146 [[nodiscard]] friend constexpr ProfileFormats operator~(ProfileFormats a) noexcept {
147 return ProfileFormats{static_cast<uint8_t>(~a.bits)};
148 }
149
158 [[nodiscard]] friend constexpr ProfileFormats operator&(ProfileFormats a, ProfileFormats b) noexcept {
159 return ProfileFormats{static_cast<uint8_t>(a.bits & b.bits)};
160 }
161
170 [[nodiscard]] friend constexpr ProfileFormats operator|(ProfileFormats a, ProfileFormats b) noexcept {
171 return ProfileFormats{static_cast<uint8_t>(a.bits | b.bits)};
172 }
173
183 [[nodiscard]] friend constexpr ProfileFormats operator^(ProfileFormats a, ProfileFormats b) noexcept {
184 return ProfileFormats{static_cast<uint8_t>(a.bits ^ b.bits)};
185 }
186
195 friend constexpr ProfileFormats& operator&=(ProfileFormats& a, ProfileFormats b) noexcept {
196 return a = a & b;
197 }
198
207 friend constexpr ProfileFormats& operator|=(ProfileFormats& a, ProfileFormats b) noexcept {
208 return a = a | b;
209 }
210
219 friend constexpr ProfileFormats& operator^=(ProfileFormats& a, ProfileFormats b) noexcept {
220 return a = a ^ b;
221 }
222
223private:
224 constexpr explicit ProfileFormats(uint8_t bits) noexcept
225 : bits(bits) {}
226
227 uint8_t bits = 0;
228};
229
238 return ~ProfileFormats{a};
239}
240
250 return ProfileFormats{a} | ProfileFormats{b};
251}
252
253inline constexpr ProfileFormats ProfileFormats::ALL = ~ProfileFormats{};
254
255} // namespace grem
256
257#ifdef GREM_USE_PROFILING
258
259namespace grem {
260
261namespace detail {
262
263class StaticOrDynamicString {
264public:
265 template <size_t N>
266 [[nodiscard]] static constexpr StaticOrDynamicString createStatic(const char (&string)[N]) noexcept {
267 StaticOrDynamicString result{};
268 result.string.emplace<StringView>(string);
269 return result;
270 }
271
272 [[nodiscard]] static constexpr StaticOrDynamicString createStaticFromStringView(StringView string) noexcept {
273 StaticOrDynamicString result{};
274 result.string.emplace<StringView>(string);
275 return result;
276 }
277
278 [[nodiscard]] static constexpr StaticOrDynamicString createDynamic(StringView string) {
279 StaticOrDynamicString result{};
280 if (string.size() <= SMALL_STRING_LENGTH) {
281 result.string.emplace<InplaceArrayList<char, SMALL_STRING_LENGTH>>(string.begin(), string.end());
282 } else {
283 result.string.emplace<String>(string);
284 }
285 return result;
286 }
287
288 constexpr StaticOrDynamicString() noexcept = default;
289
290 constexpr operator StringView() const noexcept {
291 GREM_MATCH(string) {
292 GREM_CASE(StringView staticString) {
293 return staticString;
294 }
295 GREM_CASE(const InplaceArrayList<char, SMALL_STRING_LENGTH>& smallString) {
296 return StringView{smallString.data(), smallString.size()};
297 }
298 GREM_CASE(const String& largeString) {
299 return largeString;
300 }
301 }
302 return {};
303 }
304
305private:
306 static constexpr size_t SMALL_STRING_LENGTH = 256;
307
308 Variant<StringView, InplaceArrayList<char, SMALL_STRING_LENGTH>, String> string{};
309};
310
311struct ProfilerBlock {
312 StaticOrDynamicString string{};
313 StaticOrDynamicString shortString{};
314 size_t level = 0;
315 TimePoint startTime{};
316 TimePoint endTime{};
317};
318
319class ProfilerThread {
320public:
321 struct CaptureLock {
322 UniqueLock<Mutex> captureLock{};
323#ifdef GREM_USE_MULTITHREADING
324 ThreadID threadID{};
325 StringView threadName{};
326 size_t threadIndex = 0;
327 ThreadID parentThreadID{};
328#endif
329 Span<const ProfilerBlock> blocks{};
330 };
331
332 [[nodiscard]] static ProfilerThread& getInstance();
333
334 size_t blockLevel = 0;
335
336#ifdef GREM_USE_MULTITHREADING
337 void setThreadInfo(String newThreadName, size_t newThreadIndex, ThreadID newParentThreadID) {
338#ifdef __linux__
339 if (!newThreadName.empty()) {
340 if (pthread_setname_np(pthread_self(), newThreadName.c_str()) == ERANGE) {
341 pthread_setname_np(pthread_self(), newThreadName.substr(0, 15).c_str());
342 }
343 }
344#endif
345 const ScopedLock lock{mutex};
346 threadID = ThreadID::getCurrent();
347 threadName = std::move(newThreadName);
348 threadIndex = newThreadIndex;
349 parentThreadID = newParentThreadID;
350 }
351#endif
352
353 void submitBlock(ProfilerBlock block) {
354 const ScopedLock lock{mutex};
355 blocks.push_back(std::move(block));
356 }
357
358 void clearCapture() {
359 const ScopedLock lock{mutex};
360 blocks.clear();
361 }
362
363 [[nodiscard]] CaptureLock lockCapture() {
364 UniqueLock lock{mutex};
365#ifdef GREM_USE_MULTITHREADING
366 return CaptureLock{
367 .captureLock = std::move(lock),
368 .threadID = threadID,
369 .threadName = threadName,
370 .threadIndex = threadIndex,
371 .parentThreadID = parentThreadID,
372 .blocks = blocks,
373 };
374#else
375 return CaptureLock{
376 .captureLock = std::move(lock),
377 .blocks = blocks,
378 };
379#endif
380 }
381
382private:
383 ArrayList<ProfilerBlock> blocks{};
384 Mutex mutex{};
385#ifdef GREM_USE_MULTITHREADING
386 ThreadID threadID{};
387 String threadName{};
388 std::size_t threadIndex = 0;
389 ThreadID parentThreadID{};
390#endif
391};
392
393class Profiler {
394public:
395 [[nodiscard]] static Profiler& getInstance() {
396 static Profiler instance{};
397 return instance;
398 }
399
400 void beginFrame() {
401 const ScopedLock lock{mutex};
402 if (framesToSaveCount == 0) {
403#ifdef GREM_USE_MULTITHREADING
404 for (const UniquePointer<ProfilerThread>& profilerThread : profilerThreads) {
405 GREM_ASSERT(profilerThread);
406 profilerThread->clearCapture();
407 }
408#else
409 profilerThread.clearCapture();
410#endif
411 }
412
413 if (frameInProgress) {
414 frameStartTimes.push_back(Clock::now());
415 } else {
416 frameInProgress = true;
417 captureStartTime = UTCTimestamp::now();
418 frameStartTimes = {Clock::now()};
419 frameEndTimes.clear();
420 }
421 }
422
423 void endFrame() {
424 const ScopedLock lock{mutex};
425 if (framesToSaveCount > 0) {
426 frameEndTimes.push_back(Clock::now());
427 if (--framesToSaveCount == 0 && frameInProgress) {
428 GREM_ASSERT(!nextFrameOutputFilepathPrefix.empty());
429
430 {
431#ifdef GREM_USE_MULTITHREADING
432 ArrayList<ProfilerThread::CaptureLock> captures{};
433 for (const UniquePointer<ProfilerThread>& profilerThread : profilerThreads) {
434 GREM_ASSERT(profilerThread);
435 captures.push_back(profilerThread->lockCapture());
436 }
437
438 stableSortByAscending<&ProfilerThread::CaptureLock::threadIndex>(captures);
439
440 HashMap<ThreadID, Buffer<size_t>> children{};
441
442 Buffer<size_t> traversalStack{};
443 BitBuffer traversed(profilerThreads.size(), false);
444
445 for (size_t i = profilerThreads.size(); i-- > 0;) {
446 ProfilerThread::CaptureLock& capture = captures[i];
447 capture.threadIndex = 0;
448 if (capture.parentThreadID) {
449 children[capture.parentThreadID].push_back(i);
450 } else {
451 traversalStack.push_back(i);
452 }
453 }
454
455 size_t newThreadIndex = 0;
456 while (!traversalStack.empty()) {
457 const size_t captureIndex = traversalStack.back();
458 traversalStack.pop_back();
459
460 ProfilerThread::CaptureLock& capture = captures[captureIndex];
461 capture.threadIndex = newThreadIndex++;
462
463 if (const auto it = children.find(capture.threadID); it != children.end()) {
464 for (const size_t childIndex : it->second) {
465 if (BitBuffer::reference visited = traversed[childIndex]; !visited) {
466 visited = true;
467 traversalStack.push_back(childIndex);
468 }
469 }
470 }
471 }
472
473 stableSortByAscending<&ProfilerThread::CaptureLock::threadIndex>(captures);
474#else
475 const Array captures{profilerThread.lockCapture()};
476#endif
477
478 NativeFilesystem filesystem{};
479 if (nextFrameOutputFormats.contains(ProfileFormat::BINARY)) {
480 saveAsBinary(filesystem, captures);
481 }
482 if (nextFrameOutputFormats.contains(ProfileFormat::JSON)) {
483 saveAsJSON(filesystem, captures);
484 }
485 if (nextFrameOutputFormats.contains(ProfileFormat::TRACE_EVENT_FORMAT)) {
486 saveAsTraceEventFormat(filesystem, captures);
487 }
488 }
489
490#ifdef GREM_USE_MULTITHREADING
491 for (const UniquePointer<ProfilerThread>& profilerThread : profilerThreads) {
492 GREM_ASSERT(profilerThread);
493 profilerThread->clearCapture();
494 }
495#else
496 profilerThread.clearCapture();
497#endif
498
499 frameInProgress = false;
500 }
501 } else {
502 frameInProgress = false;
503 }
504 }
505
506 void saveFrames(size_t frameCount, String outputFilepathPrefix, ProfileFormats outputFormats) {
507 GREM_ASSERT(!outputFilepathPrefix.empty());
508 const ScopedLock lock{mutex};
509 nextFrameOutputFilepathPrefix = std::move(outputFilepathPrefix);
510 nextFrameOutputFormats = outputFormats;
511 framesToSaveCount = frameCount;
512 }
513
514private:
515 friend ProfilerThread;
516
517 Profiler() = default;
518
519 void saveAsBinary(NativeFilesystem& filesystem, Span<const ProfilerThread::CaptureLock> captures) const {
520 OutputFileHandle file = filesystem.openEmptyOutputFile(nextFrameOutputFilepathPrefix + captureStartTime.toISO8601({.timeSeparator = '.'}) + ".bin");
521
522 static constexpr Array<char, 6> FORMAT_IDENTIFIER{'\x67', '\0', '\x69', '\xDD', 'P', 'F'};
523 static constexpr Pair<uint8_t> CURRENT_FORMAT_VERSION{uint8_t{0}, uint8_t{0}};
524
525 struct Header {
526 Array<char, FORMAT_IDENTIFIER.size()> formatIdentifier;
527 uint8_t formatBackwardsCompatibilityBreakingVersion;
528 uint8_t formatExtensionVersion;
529 uint16_t timestampUTCYear;
530 uint8_t timestampUTCMonth;
531 uint8_t timestampUTCDay;
532 uint8_t timestampUTCHour;
533 uint8_t timestampUTCMinute;
534 uint8_t timestampUTCSecond;
535 uint8_t reserved0 = 0;
536 uint64_t reserved1 = 0;
537 uint64_t startTimeNanoseconds;
538 uint64_t endTimeNanoseconds;
539 Array<uint64_t, 2> reserved2{};
540 uint32_t threadCount;
541 Array<uint32_t, 5> reserved3{};
542 uint64_t threadDataOffset;
543 Array<uint64_t, 5> reserved4{};
544 };
545
546 const Header header{
547 .formatIdentifier = FORMAT_IDENTIFIER,
548 .formatBackwardsCompatibilityBreakingVersion = convertHostEndianToLittleEndian(CURRENT_FORMAT_VERSION.first),
549 .formatExtensionVersion = convertHostEndianToLittleEndian(CURRENT_FORMAT_VERSION.second),
550 .timestampUTCYear = convertHostEndianToLittleEndian(static_cast<uint16_t>(captureStartTime.year)),
551 .timestampUTCMonth = convertHostEndianToLittleEndian(static_cast<uint8_t>(captureStartTime.month)),
552 .timestampUTCDay = convertHostEndianToLittleEndian(static_cast<uint8_t>(captureStartTime.day)),
553 .timestampUTCHour = convertHostEndianToLittleEndian(static_cast<uint8_t>(captureStartTime.hour)),
554 .timestampUTCMinute = convertHostEndianToLittleEndian(static_cast<uint8_t>(captureStartTime.minute)),
555 .timestampUTCSecond = convertHostEndianToLittleEndian(static_cast<uint8_t>(captureStartTime.second)),
556 .startTimeNanoseconds = convertHostEndianToLittleEndian(uint64_t{0}),
557 .endTimeNanoseconds = convertHostEndianToLittleEndian(static_cast<uint64_t>(duration_cast<Nanoseconds>(frameEndTimes.back() - frameStartTimes.front()).count())),
558 .threadCount = convertHostEndianToLittleEndian(static_cast<uint32_t>(captures.size())),
559 .threadDataOffset = convertHostEndianToLittleEndian(static_cast<uint64_t>(sizeof(Header))),
560 };
561 file.write(asBytes(Span{&header, 1}));
562
563 size_t byteOffset = sizeof(Header);
564 static_assert(sizeof(Header) % alignof(uint64_t) == 0);
565
566 const Array<byte, alignof(uint64_t) - 1> padding{};
567
568 for (const ProfilerThread::CaptureLock& capture : captures) {
569#ifdef GREM_USE_MULTITHREADING
570 const StringView threadName = capture.threadName;
571 const uint32_t threadIndex = convertHostEndianToLittleEndian(static_cast<uint32_t>(capture.threadIndex + 1));
572 const uint32_t blockCount = convertHostEndianToLittleEndian(static_cast<uint32_t>(capture.blocks.size()));
573 const uint32_t threadNameLength = convertHostEndianToLittleEndian(static_cast<uint32_t>(capture.threadName.size()));
574#else
575 const StringView threadName = "Main thread";
576 const uint32_t threadIndex = convertHostEndianToLittleEndian(uint32_t{1});
577 const uint32_t blockCount = convertHostEndianToLittleEndian(static_cast<uint32_t>(capture.blocks.size()));
578 const uint32_t threadNameLength = convertHostEndianToLittleEndian(static_cast<uint32_t>(threadName.size()));
579#endif
580 file.write(asBytes(Span{&threadIndex, 1}));
581 file.write(asBytes(Span{&blockCount, 1}));
582 file.write(asBytes(Span{&threadNameLength, 1}));
583 file.write(asBytes(Span{threadName}));
584
585 byteOffset += sizeof(uint32_t) * 3 + threadName.size();
586 const size_t captureHeaderEnd = byteOffset;
587 byteOffset = roundUpToMultiple(byteOffset, alignof(uint64_t));
588 const size_t captureHeaderAlignmentBytes = byteOffset - captureHeaderEnd;
589 file.write(Span{padding}.first(captureHeaderAlignmentBytes));
590
591 for (const ProfilerBlock& block : capture.blocks) {
592 const StringView string{block.string};
593 const StringView shortString{block.shortString};
594 const uint64_t startTimeNanoseconds =
595 convertHostEndianToLittleEndian(static_cast<uint64_t>(duration_cast<Nanoseconds>(block.startTime - frameStartTimes.front()).count()));
596 const uint64_t endTimeNanoseconds =
597 convertHostEndianToLittleEndian(static_cast<uint64_t>(duration_cast<Nanoseconds>(block.endTime - frameStartTimes.front()).count()));
598 const uint32_t level = convertHostEndianToLittleEndian(static_cast<uint32_t>(block.level));
599 const uint32_t stringLength = convertHostEndianToLittleEndian(static_cast<uint32_t>(string.size()));
600 const uint32_t shortStringLength = convertHostEndianToLittleEndian(static_cast<uint32_t>(shortString.size()));
601 file.write(asBytes(Span{&startTimeNanoseconds, 1}));
602 file.write(asBytes(Span{&endTimeNanoseconds, 1}));
603 file.write(asBytes(Span{&level, 1}));
604 file.write(asBytes(Span{&stringLength, 1}));
605 file.write(asBytes(Span{&shortStringLength, 1}));
606 file.write(asBytes(Span{string}));
607 file.write(asBytes(Span{shortString}));
608
609 byteOffset += sizeof(uint64_t) * 2 + sizeof(uint32_t) * 3 + string.size() + shortString.size();
610 const size_t blockEnd = byteOffset;
611 byteOffset = roundUpToMultiple(byteOffset, alignof(uint64_t));
612 const size_t blockAlignmentBytes = byteOffset - blockEnd;
613 file.write(Span{padding}.first(blockAlignmentBytes));
614 }
615 }
616 }
617
618 void saveAsJSON(NativeFilesystem& filesystem, Span<const ProfilerThread::CaptureLock> captures) const {
619 json::Array jsonThreads{};
620 for (const ProfilerThread::CaptureLock& capture : captures) {
621 json::Array jsonBlocks{};
622 for (const ProfilerBlock& block : capture.blocks) {
623 jsonBlocks.emplace_back(json::Object{
624 {"string", StringView{block.string}},
625 {"shortString", StringView{block.shortString}},
626 {"level", block.level},
627 {"startTimeNanoseconds", duration_cast<Nanoseconds>(block.startTime - frameStartTimes.front()).count()},
628 {"endTimeNanoseconds", duration_cast<Nanoseconds>(block.endTime - frameStartTimes.front()).count()},
629 });
630 }
631
632 jsonThreads.emplace_back(json::Object{
633#ifdef GREM_USE_MULTITHREADING
634 {"threadName", capture.threadName},
635 {"threadIndex", capture.threadIndex + 1},
636#else
637 {"threadName", "Main thread"},
638 {"threadIndex", 1},
639#endif
640 {"blocks", std::move(jsonBlocks)},
641 });
642 }
643
644 OutputFileHandle file = filesystem.openEmptyOutputFile(nextFrameOutputFilepathPrefix + captureStartTime.toISO8601({.timeSeparator = '.'}) + ".json");
645 *static_cast<NativeOutputFile*>(file.get())
646 << json::Object{
647 {"timestamp", captureStartTime.toISO8601()},
648 {"startTimeNanoseconds", 0},
649 {"endTimeNanoseconds", duration_cast<Nanoseconds>(frameEndTimes.back() - frameStartTimes.front()).count()},
650 {"threads", std::move(jsonThreads)},
651 }
652 << "\r\n";
653 }
654
655 void saveAsTraceEventFormat(Filesystem& filesystem, Span<const ProfilerThread::CaptureLock> captures) const {
656 struct Event {
657 StringView string;
658 StringView shortString;
659 char phase;
660 size_t threadID;
661 TimePoint timestamp;
662 };
663
664 json::Array jsonTraceEvents{};
665
666 Buffer<Event> events{};
667 size_t threadID = 1;
668 for (const ProfilerThread::CaptureLock& capture : captures) {
669#ifdef GREM_USE_MULTITHREADING
670 if (!capture.threadName.empty()) {
671 jsonTraceEvents.emplace_back(json::Object{
672 {"name", "thread_name"},
673 {"cat", "PERF"},
674 {"ph", "M"},
675 {"pid", 1},
676 {"tid", threadID},
677 {"args", json::Object{{"name", capture.threadName}}},
678 });
679 }
680 jsonTraceEvents.emplace_back(json::Object{
681 {"name", "thread_sort_index"},
682 {"cat", "PERF"},
683 {"ph", "M"},
684 {"pid", 1},
685 {"tid", threadID},
686 {"args", json::Object{{"sort_index", threadID}}},
687 });
688#endif
689 for (const ProfilerBlock& block : capture.blocks) {
690 events.push_back(Event{.string = block.string, .shortString = block.shortString, .phase = 'B', .threadID = threadID, .timestamp = block.startTime});
691 events.push_back(Event{.string = block.string, .shortString = block.shortString, .phase = 'E', .threadID = threadID, .timestamp = block.endTime});
692 }
693 ++threadID;
694 }
695 for (const TimePoint startTime : frameStartTimes) {
696 events.push_back(Event{.string = "Frame Start", .shortString{}, .phase = 'i', .threadID = 1, .timestamp = startTime});
697 }
698 for (const TimePoint endTime : frameEndTimes) {
699 events.push_back(Event{.string = "Frame End", .shortString{}, .phase = 'i', .threadID = 1, .timestamp = endTime});
700 }
701
702 stableSortByAscending<&Event::timestamp>(events);
703
704 for (const Event& event : events) {
705 json::Object jsonEvent{
706 {"name", (event.shortString.empty()) ? event.string : event.shortString},
707 {"cat", "PERF"},
708 {"ph", String{event.phase}},
709 {"ts", duration_cast<DurationBase<double, Ratio<1, 1'000'000>>>(event.timestamp - frameStartTimes.front()).count()},
710 {"pid", 1},
711 {"tid", event.threadID},
712 };
713 if (!event.shortString.empty()) {
714 jsonEvent["args"] = json::Object{{"fullName", event.string}};
715 }
716 if (event.phase == 'i') {
717 jsonEvent["s"] = "p";
718 }
719 jsonTraceEvents.emplace_back(std::move(jsonEvent));
720 }
721
722 OutputFileHandle file = filesystem.openEmptyOutputFile(nextFrameOutputFilepathPrefix + captureStartTime.toISO8601({.timeSeparator = '.'}) + "_trace_event_format.json");
723 *static_cast<NativeOutputFile*>(file.get()) << json::Object{{"traceEvents", std::move(jsonTraceEvents)}} << "\r\n";
724 }
725
726#ifdef GREM_USE_MULTITHREADING
727 [[nodiscard]] ProfilerThread& addThread() {
728 const ScopedLock lock{mutex};
729 return *profilerThreads.emplace_back(UniquePointer<ProfilerThread>::create());
730 }
731
732 ArrayList<UniquePointer<ProfilerThread>> profilerThreads{};
733#else
734 ProfilerThread profilerThread{};
735#endif
736 Mutex mutex{};
737 bool frameInProgress = false;
738 UTCTimestamp captureStartTime{};
739 Buffer<TimePoint> frameStartTimes{};
740 Buffer<TimePoint> frameEndTimes{};
741 String nextFrameOutputFilepathPrefix{};
742 ProfileFormats nextFrameOutputFormats{};
743 size_t framesToSaveCount = 0;
744};
745
746inline ProfilerThread& ProfilerThread::getInstance() {
747#ifdef GREM_USE_MULTITHREADING
748 thread_local ProfilerThread& instance = Profiler::getInstance().addThread();
749 return instance;
750#else
751 return Profiler::getInstance().profilerThread;
752#endif
753}
754
755class BlockProfiler {
756public:
757 explicit BlockProfiler(StaticOrDynamicString string, StaticOrDynamicString shortString)
758 : string(std::move(string))
759 , shortString(std::move(shortString)) {
760 ++ProfilerThread::getInstance().blockLevel;
761 }
762
763 ~BlockProfiler() {
764 try {
765 stop();
766 } catch (...) {
767 }
768 }
769
770 BlockProfiler(const BlockProfiler&) = delete;
771 BlockProfiler(BlockProfiler&&) = delete;
772 BlockProfiler& operator=(const BlockProfiler&) = delete;
773 BlockProfiler& operator=(BlockProfiler&&) = delete;
774
775 void stop() {
776 if (stopped) {
777 [[unlikely]] return;
778 }
779 stopped = true;
780 const TimePoint endTime = Clock::now();
781 ProfilerThread& profilerThread = ProfilerThread::getInstance();
782 const size_t level = --profilerThread.blockLevel;
783 profilerThread.submitBlock(ProfilerBlock{
784 .string = std::move(string),
785 .shortString = std::move(shortString),
786 .level = level,
787 .startTime = startTime,
788 .endTime = endTime,
789 });
790 }
791
792private:
793 StaticOrDynamicString string;
794 StaticOrDynamicString shortString;
795 TimePoint startTime = Clock::now();
796 bool stopped = false;
797};
798
799class BlockProfilerStopper {
800public:
801 explicit BlockProfilerStopper(BlockProfiler& blockProfiler) {
802 blockProfiler.stop();
803 }
804};
805
806[[nodiscard]] constexpr StringView getUnqualifiedFunctionName(StringView fullFunctionName) {
807 StringView unqualifiedFunctionName = fullFunctionName;
808 if (unqualifiedFunctionName.ends_with(')')) {
809 size_t level = 1;
810 unqualifiedFunctionName.remove_suffix(1);
811 while (!unqualifiedFunctionName.empty()) {
812 if (unqualifiedFunctionName.back() == ')') {
813 ++level;
814 } else if (unqualifiedFunctionName.back() == '(') {
815 if (--level == 0) {
816 unqualifiedFunctionName.remove_suffix(1);
817 break;
818 }
819 }
820 unqualifiedFunctionName.remove_suffix(1);
821 }
822 }
823 if (const size_t lastNameSpecifierPosition = unqualifiedFunctionName.rfind("::"); lastNameSpecifierPosition != StringView::npos) {
824 unqualifiedFunctionName = unqualifiedFunctionName.substr(lastNameSpecifierPosition + 2);
825 }
826 if (!unqualifiedFunctionName.empty() &&
827 allOf(unqualifiedFunctionName, [](const char ch) -> bool { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_'; })) {
828 return unqualifiedFunctionName;
829 }
830 return fullFunctionName;
831}
832
833[[nodiscard]] constexpr StringView getQualifiedShortFunctionName(StringView fullFunctionName, StringView shortFunctionName) {
834 if (const size_t functionNameOffset = fullFunctionName.find(shortFunctionName); functionNameOffset != StringView::npos) {
835 fullFunctionName = fullFunctionName.substr(0, functionNameOffset + shortFunctionName.size());
836 if (functionNameOffset > 2 && fullFunctionName[functionNameOffset - 1] == ':' && fullFunctionName[functionNameOffset - 2] == ':') {
837 size_t typeNameOffset = functionNameOffset - 2;
838 size_t level = 0;
839 while (typeNameOffset > 0) {
840 const char previousCharacter = fullFunctionName[typeNameOffset - 1];
841 if (level == 0 && contains(" \t(){}[]'`:", previousCharacter)) {
842 break;
843 }
844 if (previousCharacter == '>') {
845 ++level;
846 } else if (previousCharacter == '<') {
847 if (level == 0) {
848 typeNameOffset = 0;
849 break;
850 }
851 --level;
852 }
853 --typeNameOffset;
854 }
855 if (typeNameOffset == functionNameOffset - 2) {
856 typeNameOffset = functionNameOffset;
857 }
858 return fullFunctionName.substr(typeNameOffset);
859 }
860 }
861 return shortFunctionName;
862}
863
864} // namespace detail
865
866} // namespace grem
867
868#ifdef GREM_USE_MULTITHREADING
869#define GREM_PROFILER_SET_THREAD_INFO(threadName, threadIndex, parentThreadID) (grem::detail::ProfilerThread::getInstance().setThreadInfo(threadName, threadIndex, parentThreadID))
870#else
871#define GREM_PROFILER_SET_THREAD_INFO(threadName, threadIndex, parentThreadID) ((void)0)
872#endif
873#define GREM_PRIVATE_PROFILING_CONCAT(a, b) a##b
874#define GREM_PRIVATE_PROFILING_CONCAT_INDIRECT(a, b) GREM_PRIVATE_PROFILING_CONCAT(a, b)
875#define GREM_PROFILER_BEGIN_FRAME() (grem::detail::Profiler::getInstance().beginFrame())
876#define GREM_PROFILER_END_FRAME() (grem::detail::Profiler::getInstance().endFrame())
877#define GREM_PROFILER_SAVE_NEXT_N_FRAMES(frameCount, outputFilepathPrefix, outputFormats) \
878 (grem::detail::Profiler::getInstance().saveFrames(frameCount, outputFilepathPrefix, outputFormats))
879#define GREM_PROFILER_SAVE_NEXT_FRAME(outputFilepathPrefix, outputFormats) GREM_PROFILER_SAVE_NEXT_N_FRAMES(1, outputFilepathPrefix, outputFormats)
880#define GREM_PROFILE_BLOCK(staticString) \
881 const grem::detail::BlockProfiler GREM_PRIVATE_PROFILING_CONCAT_INDIRECT(GREM_private_blockProfiler, __LINE__) { \
882 grem::detail::StaticOrDynamicString::createStaticFromStringView(std::source_location::current().function_name()), \
883 grem::detail::StaticOrDynamicString::createStatic(staticString) \
884 }
885#define GREM_PROFILE_BLOCK_DYNAMIC(dynamicString) \
886 const grem::detail::BlockProfiler GREM_PRIVATE_PROFILING_CONCAT_INDIRECT(GREM_private_blockProfiler, __LINE__) { \
887 grem::detail::StaticOrDynamicString::createStaticFromStringView(std::source_location::current().function_name()), \
888 grem::detail::StaticOrDynamicString::createDynamic(dynamicString) \
889 }
890#define GREM_PROFILE_FUNCTION() \
891 const grem::detail::BlockProfiler GREM_PRIVATE_PROFILING_CONCAT_INDIRECT(GREM_private_blockProfiler, __LINE__) { \
892 grem::detail::StaticOrDynamicString::createStaticFromStringView(std::source_location::current().function_name()), \
893 grem::detail::StaticOrDynamicString::createStaticFromStringView( \
894 grem::detail::getQualifiedShortFunctionName(std::source_location::current().function_name(), __func__)) \
895 }
896#define GREM_PROFILE_CONSTRUCTOR_BEGIN() \
897 grem::detail::BlockProfiler GREM_private_constructorProfiler { \
898 grem::detail::StaticOrDynamicString::createStaticFromStringView(std::source_location::current().function_name()), \
899 grem::detail::StaticOrDynamicString::createStaticFromStringView(grem::detail::getUnqualifiedFunctionName(std::source_location::current().function_name())) \
900 }
901#define GREM_PROFILE_CONSTRUCTOR_END() \
902 const grem::detail::BlockProfilerStopper GREM_private_constructorProfilerStopper { \
903 GREM_private_constructorProfiler \
904 }
905#else
906#define GREM_PROFILER_SET_THREAD_INFO(threadName, threadIndex, parentThreadID) ((void)0)
907#define GREM_PROFILER_BEGIN_FRAME() ((void)0)
908#define GREM_PROFILER_END_FRAME() ((void)0)
909#define GREM_PROFILER_SAVE_NEXT_N_FRAMES(frameCount, outputFilepathPrefix, outputFormats) ((void)0)
910#define GREM_PROFILER_SAVE_NEXT_FRAME(outputFilepathPrefix, outputFormats) ((void)0)
911#define GREM_PROFILE_BLOCK(staticString) ((void)0)
912#define GREM_PROFILE_BLOCK_DYNAMIC(dynamicString) ((void)0)
913#define GREM_PROFILE_FUNCTION() ((void)0)
914#define GREM_PROFILE_CONSTRUCTOR_BEGIN() \
915 struct GREM_private_constructorProfiler {}
916#define GREM_PROFILE_CONSTRUCTOR_END() \
917 struct GREM_private_constructorProfilerStopper {}
918#endif
919
920#endif
#define GREM_MATCH(...)
Definition Variant.hpp:1997
#define GREM_CASE(...)
Definition Variant.hpp:1998
#define GREM_ASSERT(expression)
Definition assertions.hpp:77
Set of formats to save profile data in.
Definition profiling.hpp:62
constexpr bool containsAllOf(ProfileFormats formats) const noexcept
Check if the format set contains all of the given formats.
Definition profiling.hpp:134
constexpr bool containsAnyOf(ProfileFormats formats) const noexcept
Check if the format set contains at least one of the given formats.
Definition profiling.hpp:122
static const ProfileFormats ALL
Set containing all possible object formats.
Definition profiling.hpp:67
friend constexpr ProfileFormats operator^(ProfileFormats a, ProfileFormats b) noexcept
Get the symmetric difference of two format sets.
Definition profiling.hpp:183
friend constexpr ProfileFormats operator|(ProfileFormats a, ProfileFormats b) noexcept
Get the union of two format sets.
Definition profiling.hpp:170
constexpr bool operator==(const ProfileFormats &other) const noexcept=default
Compare this format set to another for equality.
constexpr ProfileFormats() noexcept=default
Construct an empty format set.
constexpr bool empty() const noexcept
Check if the format set is empty.
Definition profiling.hpp:99
friend constexpr ProfileFormats & operator|=(ProfileFormats &a, ProfileFormats b) noexcept
Assign the union of two format sets to the first set.
Definition profiling.hpp:207
friend constexpr ProfileFormats & operator&=(ProfileFormats &a, ProfileFormats b) noexcept
Assign the intersection of two format sets to the first set.
Definition profiling.hpp:195
friend constexpr ProfileFormats operator~(ProfileFormats a) noexcept
Get the complement of a format set.
Definition profiling.hpp:146
friend constexpr ProfileFormats operator&(ProfileFormats a, ProfileFormats b) noexcept
Get the intersection of two format sets.
Definition profiling.hpp:158
friend constexpr ProfileFormats & operator^=(ProfileFormats &a, ProfileFormats b) noexcept
Assign the symmetric difference of two format sets to the first set.
Definition profiling.hpp:219
constexpr bool contains(ProfileFormat format) const noexcept
Check if the format set contains the given format.
Definition profiling.hpp:110
size_type size() const noexcept
Definition json.hpp:7995
reference emplace_back(Args &&... args)
Definition json.hpp:8243
json::ObjectBase< std::allocator > Object
JSON object type using the default allocator.
Definition json.hpp:389
json::ArrayBase< std::allocator > Array
JSON array type using the default allocator.
Definition json.hpp:522
Definition aliases.hpp:9
GREM_ALWAYS_INLINE constexpr T convertHostEndianToLittleEndian(T value)
Convert a value in host-endian byte order to the corresponding value in little-endian byte order.
Definition fundamentals.hpp:505
Clock::time_point TimePoint
Definition Clock.hpp:26
std::ratio< Num, Den > Ratio
Definition time.hpp:19
GREM_ALWAYS_INLINE void lock(Lockable1 &lock1, Lockable2 &lock2, LockableN &... lockN)
Definition synchronization.hpp:1268
constexpr auto move(input_range auto &&range, auto outputIterator)
Definition algorithms.hpp:669
GREM_ALWAYS_INLINE constexpr vec< 1, T > GREM_VECTORCALL operator|(vec< 1, T > a, vec< 1, T > b)
Definition math.hpp:1752
GREM_ALWAYS_INLINE constexpr UnsignedInteger roundUpToMultiple(UnsignedInteger value, UnsignedInteger n)
Get the smallest multiple of n that is not greater than a given value.
Definition fundamentals.hpp:822
BitBufferBase<> BitBuffer
Definition BitBuffer.hpp:700
std::chrono::duration< Rep, Period > DurationBase
Definition time.hpp:39
StringBase< char, std::char_traits< char >, std::allocator< char > > String
Definition String.hpp:17
ProfileFormat
Format to save profile data in.
Definition profiling.hpp:53
@ JSON
Generic JSON format.
Definition profiling.hpp:55
@ TRACE_EVENT_FORMAT
Trace Event Format compatible with Perfetto and Chromium's about:tracing.
Definition profiling.hpp:56
@ BINARY
Generic binary format.
Definition profiling.hpp:54
constexpr bool contains(input_range auto &&range, const auto &value)
Definition algorithms.hpp:299
GREM_ALWAYS_INLINE constexpr vec< 1, T > GREM_VECTORCALL operator~(vec< 1, T > a)
Definition math.hpp:1751
StringViewBase< char, std::char_traits< char > > StringView
Definition StringView.hpp:16
constexpr bool allOf(input_range auto &&range, auto predicate)
Definition algorithms.hpp:226
auto asBytes(Span< T, N > s) noexcept
Definition Span.hpp:359