2 // Copyright © 2017 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
6 #include "ProfilingUtils.hpp"
8 #include <armnn/Version.hpp>
9 #include <armnn/Conversion.hpp>
11 #include <WallClockTimer.hpp>
13 #include <boost/assert.hpp>
28 void ThrowIfCantGenerateNextUid(uint16_t uid, uint16_t cores = 0)
30 // Check that it is possible to generate the next UID without causing an overflow
35 // Number of cores not specified or set to 1 (a value of zero indicates the device is not capable of
36 // running multiple parallel workloads and will not provide multiple streams of data for each event)
37 if (uid == std::numeric_limits<uint16_t>::max())
39 throw RuntimeException("Generating the next UID for profiling would result in an overflow");
43 // Multiple cores available, as max_counter_uid has to be set to: counter_uid + cores - 1, the maximum
44 // allowed value for a counter UID is consequently: uint16_t_max - cores + 1
45 if (uid >= std::numeric_limits<uint16_t>::max() - cores + 1)
47 throw RuntimeException("Generating the next UID for profiling would result in an overflow");
53 } // Anonymous namespace
55 uint16_t GetNextUid(bool peekOnly)
57 // The UID used for profiling objects and events. The first valid UID is 1, as 0 is a reserved value
58 static uint16_t uid = 1;
60 // Check that it is possible to generate the next UID without causing an overflow (throws in case of error)
61 ThrowIfCantGenerateNextUid(uid);
75 std::vector<uint16_t> GetNextCounterUids(uint16_t cores)
77 // The UID used for counters only. The first valid UID is 0
78 static uint16_t counterUid = 0;
80 // Check that it is possible to generate the next counter UID without causing an overflow (throws in case of error)
81 ThrowIfCantGenerateNextUid(counterUid, cores);
83 // Get the next counter UIDs
84 size_t counterUidsSize = cores == 0 ? 1 : cores;
85 std::vector<uint16_t> counterUids(counterUidsSize, 0);
86 for (size_t i = 0; i < counterUidsSize; i++)
88 counterUids[i] = counterUid++;
93 void WriteBytes(const IPacketBufferPtr& packetBuffer, unsigned int offset, const void* value, unsigned int valueSize)
95 BOOST_ASSERT(packetBuffer);
97 WriteBytes(packetBuffer->GetWritableData(), offset, value, valueSize);
100 uint32_t ConstructHeader(uint32_t packetFamily,
103 return ((packetFamily & 0x3F) << 26)|
104 ((packetId & 0x3FF) << 16);
107 uint32_t ConstructHeader(uint32_t packetFamily,
108 uint32_t packetClass,
111 return ((packetFamily & 0x3F) << 26)|
112 ((packetClass & 0x3FF) << 19)|
113 ((packetType & 0x3FFF) << 16);
116 void WriteUint64(const std::unique_ptr<IPacketBuffer>& packetBuffer, unsigned int offset, uint64_t value)
118 BOOST_ASSERT(packetBuffer);
120 WriteUint64(packetBuffer->GetWritableData(), offset, value);
123 void WriteUint32(const IPacketBufferPtr& packetBuffer, unsigned int offset, uint32_t value)
125 BOOST_ASSERT(packetBuffer);
127 WriteUint32(packetBuffer->GetWritableData(), offset, value);
130 void WriteUint16(const IPacketBufferPtr& packetBuffer, unsigned int offset, uint16_t value)
132 BOOST_ASSERT(packetBuffer);
134 WriteUint16(packetBuffer->GetWritableData(), offset, value);
137 void WriteBytes(unsigned char* buffer, unsigned int offset, const void* value, unsigned int valueSize)
139 BOOST_ASSERT(buffer);
142 for (unsigned int i = 0; i < valueSize; i++, offset++)
144 buffer[offset] = *(reinterpret_cast<const unsigned char*>(value) + i);
148 void WriteUint64(unsigned char* buffer, unsigned int offset, uint64_t value)
150 BOOST_ASSERT(buffer);
152 buffer[offset] = static_cast<unsigned char>(value & 0xFF);
153 buffer[offset + 1] = static_cast<unsigned char>((value >> 8) & 0xFF);
154 buffer[offset + 2] = static_cast<unsigned char>((value >> 16) & 0xFF);
155 buffer[offset + 3] = static_cast<unsigned char>((value >> 24) & 0xFF);
156 buffer[offset + 4] = static_cast<unsigned char>((value >> 32) & 0xFF);
157 buffer[offset + 5] = static_cast<unsigned char>((value >> 40) & 0xFF);
158 buffer[offset + 6] = static_cast<unsigned char>((value >> 48) & 0xFF);
159 buffer[offset + 7] = static_cast<unsigned char>((value >> 56) & 0xFF);
162 void WriteUint32(unsigned char* buffer, unsigned int offset, uint32_t value)
164 BOOST_ASSERT(buffer);
166 buffer[offset] = static_cast<unsigned char>(value & 0xFF);
167 buffer[offset + 1] = static_cast<unsigned char>((value >> 8) & 0xFF);
168 buffer[offset + 2] = static_cast<unsigned char>((value >> 16) & 0xFF);
169 buffer[offset + 3] = static_cast<unsigned char>((value >> 24) & 0xFF);
172 void WriteUint16(unsigned char* buffer, unsigned int offset, uint16_t value)
174 BOOST_ASSERT(buffer);
176 buffer[offset] = static_cast<unsigned char>(value & 0xFF);
177 buffer[offset + 1] = static_cast<unsigned char>((value >> 8) & 0xFF);
180 void ReadBytes(const IPacketBufferPtr& packetBuffer, unsigned int offset, unsigned int valueSize, uint8_t outValue[])
182 BOOST_ASSERT(packetBuffer);
184 ReadBytes(packetBuffer->GetReadableData(), offset, valueSize, outValue);
187 uint64_t ReadUint64(const IPacketBufferPtr& packetBuffer, unsigned int offset)
189 BOOST_ASSERT(packetBuffer);
191 return ReadUint64(packetBuffer->GetReadableData(), offset);
194 uint32_t ReadUint32(const IPacketBufferPtr& packetBuffer, unsigned int offset)
196 BOOST_ASSERT(packetBuffer);
198 return ReadUint32(packetBuffer->GetReadableData(), offset);
201 uint16_t ReadUint16(const IPacketBufferPtr& packetBuffer, unsigned int offset)
203 BOOST_ASSERT(packetBuffer);
205 return ReadUint16(packetBuffer->GetReadableData(), offset);
208 uint8_t ReadUint8(const IPacketBufferPtr& packetBuffer, unsigned int offset)
210 BOOST_ASSERT(packetBuffer);
212 return ReadUint8(packetBuffer->GetReadableData(), offset);
215 void ReadBytes(const unsigned char* buffer, unsigned int offset, unsigned int valueSize, uint8_t outValue[])
217 BOOST_ASSERT(buffer);
218 BOOST_ASSERT(outValue);
220 for (unsigned int i = 0; i < valueSize; i++, offset++)
222 outValue[i] = static_cast<uint8_t>(buffer[offset]);
226 uint64_t ReadUint64(const unsigned char* buffer, unsigned int offset)
228 BOOST_ASSERT(buffer);
231 value = static_cast<uint64_t>(buffer[offset]);
232 value |= static_cast<uint64_t>(buffer[offset + 1]) << 8;
233 value |= static_cast<uint64_t>(buffer[offset + 2]) << 16;
234 value |= static_cast<uint64_t>(buffer[offset + 3]) << 24;
235 value |= static_cast<uint64_t>(buffer[offset + 4]) << 32;
236 value |= static_cast<uint64_t>(buffer[offset + 5]) << 40;
237 value |= static_cast<uint64_t>(buffer[offset + 6]) << 48;
238 value |= static_cast<uint64_t>(buffer[offset + 7]) << 56;
243 uint32_t ReadUint32(const unsigned char* buffer, unsigned int offset)
245 BOOST_ASSERT(buffer);
248 value = static_cast<uint32_t>(buffer[offset]);
249 value |= static_cast<uint32_t>(buffer[offset + 1]) << 8;
250 value |= static_cast<uint32_t>(buffer[offset + 2]) << 16;
251 value |= static_cast<uint32_t>(buffer[offset + 3]) << 24;
255 uint16_t ReadUint16(const unsigned char* buffer, unsigned int offset)
257 BOOST_ASSERT(buffer);
260 value = static_cast<uint32_t>(buffer[offset]);
261 value |= static_cast<uint32_t>(buffer[offset + 1]) << 8;
262 return static_cast<uint16_t>(value);
265 uint8_t ReadUint8(const unsigned char* buffer, unsigned int offset)
267 BOOST_ASSERT(buffer);
269 return buffer[offset];
272 std::string GetSoftwareInfo()
274 return std::string("ArmNN");
277 std::string GetHardwareVersion()
279 return std::string();
282 std::string GetSoftwareVersion()
284 std::string armnnVersion(ARMNN_VERSION);
285 std::string result = "Armnn " + armnnVersion.substr(2,2) + "." + armnnVersion.substr(4,2);
289 std::string GetProcessName()
291 std::ifstream comm("/proc/self/comm");
297 /// Creates a timeline packet header
300 /// packetFamiliy Timeline Packet Family
301 /// packetClass Timeline Packet Class
302 /// packetType Timeline Packet Type
303 /// streamId Stream identifier
304 /// seqeunceNumbered When non-zero the 4 bytes following the header is a u32 sequence number
305 /// dataLength Unsigned 24-bit integer. Length of data, in bytes. Zero is permitted
308 /// Pair of uint32_t containing word0 and word1 of the header
309 std::pair<uint32_t, uint32_t> CreateTimelinePacketHeader(uint32_t packetFamily,
310 uint32_t packetClass,
313 uint32_t sequenceNumbered,
316 // Packet header word 0:
317 // 26:31 [6] packet_family: timeline Packet Family, value 0b000001
318 // 19:25 [7] packet_class: packet class
319 // 16:18 [3] packet_type: packet type
320 // 8:15 [8] reserved: all zeros
321 // 0:7 [8] stream_id: stream identifier
322 uint32_t packetHeaderWord0 = ((packetFamily & 0x0000003F) << 26) |
323 ((packetClass & 0x0000007F) << 19) |
324 ((packetType & 0x00000007) << 16) |
325 ((streamId & 0x00000007) << 0);
327 // Packet header word 1:
328 // 25:31 [7] reserved: all zeros
329 // 24 [1] sequence_numbered: when non-zero the 4 bytes following the header is a u32 sequence number
330 // 0:23 [24] data_length: unsigned 24-bit integer. Length of data, in bytes. Zero is permitted
331 uint32_t packetHeaderWord1 = ((sequenceNumbered & 0x00000001) << 24) |
332 ((dataLength & 0x00FFFFFF) << 0);
334 return std::make_pair(packetHeaderWord0, packetHeaderWord1);
337 // Calculate the actual length an SwString will be including the terminating null character
338 // padding to bring it to the next uint32_t boundary but minus the leading uint32_t encoding
339 // the size to allow the offset to be correctly updated when decoding a binary packet.
340 uint32_t CalculateSizeOfPaddedSwString(const std::string& str)
342 std::vector<uint32_t> swTraceString;
343 StringToSwTraceString<SwTraceCharPolicy>(str, swTraceString);
344 unsigned int uint32_t_size = sizeof(uint32_t);
345 uint32_t size = (boost::numeric_cast<uint32_t>(swTraceString.size()) - 1) * uint32_t_size;
349 // Read TimelineMessageDirectoryPacket from given IPacketBuffer and offset
350 SwTraceMessage ReadSwTraceMessage(const IPacketBufferPtr& packetBuffer, unsigned int& offset)
352 BOOST_ASSERT(packetBuffer);
354 unsigned int uint32_t_size = sizeof(uint32_t);
356 SwTraceMessage swTraceMessage;
359 uint32_t readDeclId = ReadUint32(packetBuffer, offset);
360 swTraceMessage.id = readDeclId;
362 // SWTrace "namestring" format
363 // length of the string (first 4 bytes) + string + null terminator
365 // Check the decl_name
366 offset += uint32_t_size;
367 uint32_t swTraceDeclNameLength = ReadUint32(packetBuffer, offset);
369 offset += uint32_t_size;
370 std::vector<unsigned char> swTraceStringBuffer(swTraceDeclNameLength - 1);
371 std::memcpy(swTraceStringBuffer.data(),
372 packetBuffer->GetReadableData() + offset, swTraceStringBuffer.size());
374 swTraceMessage.name.assign(swTraceStringBuffer.begin(), swTraceStringBuffer.end()); // name
377 offset += CalculateSizeOfPaddedSwString(swTraceMessage.name);
378 uint32_t swTraceUINameLength = ReadUint32(packetBuffer, offset);
380 offset += uint32_t_size;
381 swTraceStringBuffer.resize(swTraceUINameLength - 1);
382 std::memcpy(swTraceStringBuffer.data(),
383 packetBuffer->GetReadableData() + offset, swTraceStringBuffer.size());
385 swTraceMessage.uiName.assign(swTraceStringBuffer.begin(), swTraceStringBuffer.end()); // ui_name
388 offset += CalculateSizeOfPaddedSwString(swTraceMessage.uiName);
389 uint32_t swTraceArgTypesLength = ReadUint32(packetBuffer, offset);
391 offset += uint32_t_size;
392 swTraceStringBuffer.resize(swTraceArgTypesLength - 1);
393 std::memcpy(swTraceStringBuffer.data(),
394 packetBuffer->GetReadableData() + offset, swTraceStringBuffer.size());
396 swTraceMessage.argTypes.assign(swTraceStringBuffer.begin(), swTraceStringBuffer.end()); // arg_types
398 std::string swTraceString(swTraceStringBuffer.begin(), swTraceStringBuffer.end());
401 offset += CalculateSizeOfPaddedSwString(swTraceString);
402 uint32_t swTraceArgNamesLength = ReadUint32(packetBuffer, offset);
404 offset += uint32_t_size;
405 swTraceStringBuffer.resize(swTraceArgNamesLength - 1);
406 std::memcpy(swTraceStringBuffer.data(),
407 packetBuffer->GetReadableData() + offset, swTraceStringBuffer.size());
409 swTraceString.assign(swTraceStringBuffer.begin(), swTraceStringBuffer.end());
410 std::stringstream stringStream(swTraceString);
412 while (std::getline(stringStream, argName, ','))
414 swTraceMessage.argNames.push_back(argName);
417 offset += CalculateSizeOfPaddedSwString(swTraceString);
419 return swTraceMessage;
422 /// Creates a packet header for the timeline messages:
425 /// * declareEventClass
426 /// * declareRelationship
430 /// dataLength The length of the message body in bytes
433 /// Pair of uint32_t containing word0 and word1 of the header
434 std::pair<uint32_t, uint32_t> CreateTimelineMessagePacketHeader(unsigned int dataLength)
436 return CreateTimelinePacketHeader(1, // Packet family
440 0, // Sequence number
441 dataLength); // Data length
444 TimelinePacketStatus WriteTimelineLabelBinaryPacket(uint64_t profilingGuid,
445 const std::string& label,
446 unsigned char* buffer,
447 unsigned int bufferSize,
448 unsigned int& numberOfBytesWritten)
450 // Initialize the output value
451 numberOfBytesWritten = 0;
453 // Check that the given buffer is valid
454 if (buffer == nullptr || bufferSize == 0)
456 return TimelinePacketStatus::BufferExhaustion;
460 unsigned int uint32_t_size = sizeof(uint32_t);
461 unsigned int uint64_t_size = sizeof(uint64_t);
463 // Convert the label into a SWTrace string
464 std::vector<uint32_t> swTraceLabel;
465 bool result = StringToSwTraceString<SwTraceCharPolicy>(label, swTraceLabel);
468 return TimelinePacketStatus::Error;
471 // Calculate the size of the SWTrace string label (in bytes)
472 unsigned int swTraceLabelSize = boost::numeric_cast<unsigned int>(swTraceLabel.size()) * uint32_t_size;
474 // Calculate the length of the data (in bytes)
475 unsigned int timelineLabelPacketDataLength = uint32_t_size + // decl_Id
476 uint64_t_size + // Profiling GUID
477 swTraceLabelSize; // Label
479 // Calculate the timeline binary packet size (in bytes)
480 unsigned int timelineLabelPacketSize = 2 * uint32_t_size + // Header (2 words)
481 timelineLabelPacketDataLength; // decl_Id + Profiling GUID + label
483 // Check whether the timeline binary packet fits in the given buffer
484 if (timelineLabelPacketSize > bufferSize)
486 return TimelinePacketStatus::BufferExhaustion;
489 // Create packet header
490 std::pair<uint32_t, uint32_t> packetHeader = CreateTimelineMessagePacketHeader(timelineLabelPacketDataLength);
492 // Initialize the offset for writing in the buffer
493 unsigned int offset = 0;
495 // Write the timeline binary packet header to the buffer
496 WriteUint32(buffer, offset, packetHeader.first);
497 offset += uint32_t_size;
498 WriteUint32(buffer, offset, packetHeader.second);
499 offset += uint32_t_size;
501 // Write decl_Id to the buffer
502 WriteUint32(buffer, offset, 0u);
503 offset += uint32_t_size;
505 // Write the timeline binary packet payload to the buffer
506 WriteUint64(buffer, offset, profilingGuid); // Profiling GUID
507 offset += uint64_t_size;
508 for (uint32_t swTraceLabelWord : swTraceLabel)
510 WriteUint32(buffer, offset, swTraceLabelWord); // Label
511 offset += uint32_t_size;
514 // Update the number of bytes written
515 numberOfBytesWritten = timelineLabelPacketSize;
517 return TimelinePacketStatus::Ok;
520 TimelinePacketStatus WriteTimelineEntityBinaryPacket(uint64_t profilingGuid,
521 unsigned char* buffer,
522 unsigned int bufferSize,
523 unsigned int& numberOfBytesWritten)
525 // Initialize the output value
526 numberOfBytesWritten = 0;
528 // Check that the given buffer is valid
529 if (buffer == nullptr || bufferSize == 0)
531 return TimelinePacketStatus::BufferExhaustion;
535 unsigned int uint32_t_size = sizeof(uint32_t);
536 unsigned int uint64_t_size = sizeof(uint64_t);
538 // Calculate the length of the data (in bytes)
539 unsigned int timelineEntityPacketDataLength = uint64_t_size; // Profiling GUID
542 // Calculate the timeline binary packet size (in bytes)
543 unsigned int timelineEntityPacketSize = 2 * uint32_t_size + // Header (2 words)
544 uint32_t_size + // decl_Id
545 timelineEntityPacketDataLength; // Profiling GUID
547 // Check whether the timeline binary packet fits in the given buffer
548 if (timelineEntityPacketSize > bufferSize)
550 return TimelinePacketStatus::BufferExhaustion;
553 // Create packet header
554 std::pair<uint32_t, uint32_t> packetHeader = CreateTimelineMessagePacketHeader(timelineEntityPacketDataLength);
556 // Initialize the offset for writing in the buffer
557 unsigned int offset = 0;
559 // Write the timeline binary packet header to the buffer
560 WriteUint32(buffer, offset, packetHeader.first);
561 offset += uint32_t_size;
562 WriteUint32(buffer, offset, packetHeader.second);
563 offset += uint32_t_size;
565 // Write the decl_Id to the buffer
566 WriteUint32(buffer, offset, 1u);
567 offset += uint32_t_size;
569 // Write the timeline binary packet payload to the buffer
570 WriteUint64(buffer, offset, profilingGuid); // Profiling GUID
572 // Update the number of bytes written
573 numberOfBytesWritten = timelineEntityPacketSize;
575 return TimelinePacketStatus::Ok;
578 TimelinePacketStatus WriteTimelineRelationshipBinaryPacket(ProfilingRelationshipType relationshipType,
579 uint64_t relationshipGuid,
582 unsigned char* buffer,
583 unsigned int bufferSize,
584 unsigned int& numberOfBytesWritten)
586 // Initialize the output value
587 numberOfBytesWritten = 0;
589 // Check that the given buffer is valid
590 if (buffer == nullptr || bufferSize == 0)
592 return TimelinePacketStatus::BufferExhaustion;
596 unsigned int uint32_t_size = sizeof(uint32_t);
597 unsigned int uint64_t_size = sizeof(uint64_t);
599 // Calculate the length of the data (in bytes)
600 unsigned int timelineRelationshipPacketDataLength = uint32_t_size * 2 + // decl_id + Relationship Type
601 uint64_t_size * 3; // Relationship GUID + Head GUID + tail GUID
603 // Calculate the timeline binary packet size (in bytes)
604 unsigned int timelineRelationshipPacketSize = 2 * uint32_t_size + // Header (2 words)
605 timelineRelationshipPacketDataLength;
607 // Check whether the timeline binary packet fits in the given buffer
608 if (timelineRelationshipPacketSize > bufferSize)
610 return TimelinePacketStatus::BufferExhaustion;
613 // Create packet header
614 uint32_t dataLength = boost::numeric_cast<uint32_t>(timelineRelationshipPacketDataLength);
615 std::pair<uint32_t, uint32_t> packetHeader = CreateTimelineMessagePacketHeader(dataLength);
617 // Initialize the offset for writing in the buffer
618 unsigned int offset = 0;
620 // Write the timeline binary packet header to the buffer
621 WriteUint32(buffer, offset, packetHeader.first);
622 offset += uint32_t_size;
623 WriteUint32(buffer, offset, packetHeader.second);
624 offset += uint32_t_size;
626 uint32_t relationshipTypeUint = 0;
628 switch (relationshipType)
630 case ProfilingRelationshipType::RetentionLink:
631 relationshipTypeUint = 0;
633 case ProfilingRelationshipType::ExecutionLink:
634 relationshipTypeUint = 1;
636 case ProfilingRelationshipType::DataLink:
637 relationshipTypeUint = 2;
639 case ProfilingRelationshipType::LabelLink:
640 relationshipTypeUint = 3;
643 throw InvalidArgumentException("Unknown relationship type given.");
646 // Write the timeline binary packet payload to the buffer
647 // decl_id of the timeline message
649 WriteUint32(buffer, offset, declId); // decl_id
650 offset += uint32_t_size;
651 WriteUint32(buffer, offset, relationshipTypeUint); // Relationship Type
652 offset += uint32_t_size;
653 WriteUint64(buffer, offset, relationshipGuid); // GUID of this relationship
654 offset += uint64_t_size;
655 WriteUint64(buffer, offset, headGuid); // head of relationship GUID
656 offset += uint64_t_size;
657 WriteUint64(buffer, offset, tailGuid); // tail of relationship GUID
659 // Update the number of bytes written
660 numberOfBytesWritten = timelineRelationshipPacketSize;
662 return TimelinePacketStatus::Ok;
665 TimelinePacketStatus WriteTimelineMessageDirectoryPackage(unsigned char* buffer,
666 unsigned int bufferSize,
667 unsigned int& numberOfBytesWritten)
669 // Initialize the output value
670 numberOfBytesWritten = 0;
672 // Check that the given buffer is valid
673 if (buffer == nullptr || bufferSize == 0)
675 return TimelinePacketStatus::BufferExhaustion;
679 unsigned int uint32_t_size = sizeof(uint32_t);
681 // The payload/data of the packet consists of swtrace event definitions encoded according
682 // to the swtrace directory specification. The messages being the five defined below:
683 // | decl_id | decl_name | ui_name | arg_types | arg_names |
684 // |-----------|---------------------|-----------------------|-------------|-------------------------------------|
685 // | 0 | declareLabel | declare label | ps | guid,value |
686 // | 1 | declareEntity | declare entity | p | guid |
687 // | 2 | declareEventClass | declare event class | p | guid |
688 // | 3 | declareRelationship | declare relationship | Ippp | relationshipType,relationshipGuid, |
689 // | | | | | headGuid,tailGuid |
690 // | 4 | declareEvent | declare event | @tp | timestamp,threadId,eventGuid |
692 std::vector<std::vector<std::string>> timelineDirectoryMessages
694 {"declareLabel", "declare label", "ps", "guid,value"},
695 {"declareEntity", "declare entity", "p", "guid"},
696 {"declareEventClass", "declare event class", "p", "guid"},
697 {"declareRelationship", "declare relationship", "Ippp", "relationshipType,relationshipGuid,headGuid,tailGuid"},
698 {"declareEvent", "declare event", "@tp", "timestamp,threadId,eventGuid"}
701 unsigned int messagesDataLength = 0u;
702 std::vector<std::vector<std::vector<uint32_t>>> swTraceTimelineDirectoryMessages;
704 for (const auto& timelineDirectoryMessage : timelineDirectoryMessages)
706 messagesDataLength += uint32_t_size; // decl_id
708 std::vector<std::vector<uint32_t>> swTraceStringsVector;
709 for (const auto& label : timelineDirectoryMessage)
711 std::vector<uint32_t> swTraceString;
712 bool result = StringToSwTraceString<SwTraceCharPolicy>(label, swTraceString);
715 return TimelinePacketStatus::Error;
718 messagesDataLength += boost::numeric_cast<unsigned int>(swTraceString.size()) * uint32_t_size;
719 swTraceStringsVector.push_back(swTraceString);
721 swTraceTimelineDirectoryMessages.push_back(swTraceStringsVector);
724 // Calculate the timeline directory binary packet size (in bytes)
725 unsigned int timelineDirectoryPacketSize = 2 * uint32_t_size + // Header (2 words)
726 messagesDataLength; // 5 messages length
728 // Check whether the timeline directory binary packet fits in the given buffer
729 if (timelineDirectoryPacketSize > bufferSize)
731 return TimelinePacketStatus::BufferExhaustion;
734 // Create packet header
735 uint32_t dataLength = boost::numeric_cast<uint32_t>(messagesDataLength);
736 std::pair<uint32_t, uint32_t> packetHeader = CreateTimelinePacketHeader(1, 0, 0, 0, 0, dataLength);
738 // Initialize the offset for writing in the buffer
739 unsigned int offset = 0;
741 // Write the timeline binary packet header to the buffer
742 WriteUint32(buffer, offset, packetHeader.first);
743 offset += uint32_t_size;
744 WriteUint32(buffer, offset, packetHeader.second);
745 offset += uint32_t_size;
747 for (unsigned int i = 0u; i < swTraceTimelineDirectoryMessages.size(); ++i)
749 // Write the timeline binary packet payload to the buffer
750 WriteUint32(buffer, offset, i); // decl_id
751 offset += uint32_t_size;
753 for (std::vector<uint32_t> swTraceString : swTraceTimelineDirectoryMessages[i])
755 for (uint32_t swTraceDeclStringWord : swTraceString)
757 WriteUint32(buffer, offset, swTraceDeclStringWord);
758 offset += uint32_t_size;
763 // Update the number of bytes written
764 numberOfBytesWritten = timelineDirectoryPacketSize;
766 return TimelinePacketStatus::Ok;
769 TimelinePacketStatus WriteTimelineEventClassBinaryPacket(uint64_t profilingGuid,
770 unsigned char* buffer,
771 unsigned int bufferSize,
772 unsigned int& numberOfBytesWritten)
774 // Initialize the output value
775 numberOfBytesWritten = 0;
777 // Check that the given buffer is valid
778 if (buffer == nullptr || bufferSize == 0)
780 return TimelinePacketStatus::BufferExhaustion;
784 unsigned int uint32_t_size = sizeof(uint32_t);
785 unsigned int uint64_t_size = sizeof(uint64_t);
787 // decl_id of the timeline message
790 // Calculate the length of the data (in bytes)
791 unsigned int packetBodySize = uint32_t_size + uint64_t_size; // decl_id + Profiling GUID
793 // Calculate the timeline binary packet size (in bytes)
794 unsigned int packetSize = 2 * uint32_t_size + // Header (2 words)
795 packetBodySize; // Body
797 // Check whether the timeline binary packet fits in the given buffer
798 if (packetSize > bufferSize)
800 return TimelinePacketStatus::BufferExhaustion;
803 // Create packet header
804 std::pair<uint32_t, uint32_t> packetHeader = CreateTimelineMessagePacketHeader(packetBodySize);
806 // Initialize the offset for writing in the buffer
807 unsigned int offset = 0;
809 // Write the timeline binary packet header to the buffer
810 WriteUint32(buffer, offset, packetHeader.first);
811 offset += uint32_t_size;
812 WriteUint32(buffer, offset, packetHeader.second);
813 offset += uint32_t_size;
815 // Write the timeline binary packet payload to the buffer
816 WriteUint32(buffer, offset, declId); // decl_id
817 offset += uint32_t_size;
818 WriteUint64(buffer, offset, profilingGuid); // Profiling GUID
820 // Update the number of bytes written
821 numberOfBytesWritten = packetSize;
823 return TimelinePacketStatus::Ok;
826 TimelinePacketStatus WriteTimelineEventBinaryPacket(uint64_t timestamp,
827 std::thread::id threadId,
828 uint64_t profilingGuid,
829 unsigned char* buffer,
830 unsigned int bufferSize,
831 unsigned int& numberOfBytesWritten)
833 // Initialize the output value
834 numberOfBytesWritten = 0;
836 // Check that the given buffer is valid
837 if (buffer == nullptr || bufferSize == 0)
839 return TimelinePacketStatus::BufferExhaustion;
843 unsigned int uint32_t_size = sizeof(uint32_t);
844 unsigned int uint64_t_size = sizeof(uint64_t);
845 unsigned int threadId_size = sizeof(std::thread::id);
847 // decl_id of the timeline message
850 // Calculate the length of the data (in bytes)
851 unsigned int timelineEventPacketDataLength = uint32_t_size + // decl_id
852 uint64_t_size + // Timestamp
853 threadId_size + // Thread id
854 uint64_t_size; // Profiling GUID
856 // Calculate the timeline binary packet size (in bytes)
857 unsigned int timelineEventPacketSize = 2 * uint32_t_size + // Header (2 words)
858 timelineEventPacketDataLength; // Timestamp + thread id + profiling GUID
860 // Check whether the timeline binary packet fits in the given buffer
861 if (timelineEventPacketSize > bufferSize)
863 return TimelinePacketStatus::BufferExhaustion;
866 // Create packet header
867 std::pair<uint32_t, uint32_t> packetHeader = CreateTimelineMessagePacketHeader(timelineEventPacketDataLength);
869 // Initialize the offset for writing in the buffer
870 unsigned int offset = 0;
872 // Write the timeline binary packet header to the buffer
873 WriteUint32(buffer, offset, packetHeader.first);
874 offset += uint32_t_size;
875 WriteUint32(buffer, offset, packetHeader.second);
876 offset += uint32_t_size;
878 // Write the timeline binary packet payload to the buffer
879 WriteUint32(buffer, offset, declId); // decl_id
880 offset += uint32_t_size;
881 WriteUint64(buffer, offset, timestamp); // Timestamp
882 offset += uint64_t_size;
883 WriteBytes(buffer, offset, &threadId, threadId_size); // Thread id
884 offset += threadId_size;
885 WriteUint64(buffer, offset, profilingGuid); // Profiling GUID
886 offset += uint64_t_size;
888 // Update the number of bytes written
889 numberOfBytesWritten = timelineEventPacketSize;
891 return TimelinePacketStatus::Ok;
894 std::string CentreAlignFormatting(const std::string& stringToPass, const int spacingWidth)
896 std::stringstream outputStream, centrePadding;
897 int padding = spacingWidth - static_cast<int>(stringToPass.size());
899 for (int i = 0; i < padding / 2; ++i)
901 centrePadding << " ";
904 outputStream << centrePadding.str() << stringToPass << centrePadding.str();
906 if (padding > 0 && padding %2 != 0)
911 return outputStream.str();
914 void PrintDeviceDetails(const std::pair<const unsigned short, std::unique_ptr<Device>>& devicePair)
918 body.append(CentreAlignFormatting(devicePair.second->m_Name, 20));
920 body.append(CentreAlignFormatting(std::to_string(devicePair.first), 13));
922 body.append(CentreAlignFormatting(std::to_string(devicePair.second->m_Cores), 10));
925 std::cout << std::string(body.size(), '-') << "\n";
929 void PrintCounterSetDetails(const std::pair<const unsigned short, std::unique_ptr<CounterSet>>& counterSetPair)
933 body.append(CentreAlignFormatting(counterSetPair.second->m_Name, 20));
935 body.append(CentreAlignFormatting(std::to_string(counterSetPair.first), 13));
937 body.append(CentreAlignFormatting(std::to_string(counterSetPair.second->m_Count), 10));
940 std::cout << std::string(body.size(), '-') << "\n";
945 void PrintCounterDetails(std::shared_ptr<Counter>& counter)
949 body.append(CentreAlignFormatting(counter->m_Name, 20));
951 body.append(CentreAlignFormatting(counter->m_Description, 50));
953 body.append(CentreAlignFormatting(counter->m_Units, 14));
955 body.append(CentreAlignFormatting(std::to_string(counter->m_Uid), 6));
957 body.append(CentreAlignFormatting(std::to_string(counter->m_MaxCounterUid), 10));
959 body.append(CentreAlignFormatting(std::to_string(counter->m_Class), 8));
961 body.append(CentreAlignFormatting(std::to_string(counter->m_Interpolation), 14));
963 body.append(CentreAlignFormatting(std::to_string(counter->m_Multiplier), 20));
965 body.append(CentreAlignFormatting(std::to_string(counter->m_CounterSetUid), 16));
967 body.append(CentreAlignFormatting(std::to_string(counter->m_DeviceUid), 14));
971 std::cout << std::string(body.size(), '-') << "\n";
976 void PrintCategoryDetails(const std::unique_ptr<Category>& category,
977 std::unordered_map<unsigned short, std::shared_ptr<Counter>> counterMap)
979 std::string categoryBody;
980 std::string categoryHeader;
982 categoryHeader.append(CentreAlignFormatting("Name", 20));
983 categoryHeader.append(" | ");
984 categoryHeader.append(CentreAlignFormatting("Device", 12));
985 categoryHeader.append(" | ");
986 categoryHeader.append(CentreAlignFormatting("Counter set UID:", 16));
987 categoryHeader.append(" | ");
988 categoryHeader.append(CentreAlignFormatting("Event Count", 14));
989 categoryHeader.append("\n");
991 categoryBody.append(CentreAlignFormatting(category->m_Name, 20));
992 categoryBody.append(" | ");
993 categoryBody.append(CentreAlignFormatting(std::to_string(category->m_DeviceUid), 12));
994 categoryBody.append(" | ");
995 categoryBody.append(CentreAlignFormatting(std::to_string(category->m_CounterSetUid), 16));
996 categoryBody.append(" | ");
997 categoryBody.append(CentreAlignFormatting(std::to_string(category->m_Counters.size()), 14));
999 std::cout << "\n" << "\n";
1000 std::cout << CentreAlignFormatting("CATEGORY", static_cast<int>(categoryHeader.size()));
1002 std::cout << std::string(categoryHeader.size(), '=') << "\n";
1004 std::cout << categoryHeader;
1006 std::cout << std::string(categoryBody.size(), '-') << "\n";
1008 std::cout << categoryBody;
1010 std::string counterHeader;
1012 counterHeader.append(CentreAlignFormatting("Counter Name", 20));
1013 counterHeader.append(" | ");
1014 counterHeader.append(CentreAlignFormatting("Description", 50));
1015 counterHeader.append(" | ");
1016 counterHeader.append(CentreAlignFormatting("Units", 14));
1017 counterHeader.append(" | ");
1018 counterHeader.append(CentreAlignFormatting("UID", 6));
1019 counterHeader.append(" | ");
1020 counterHeader.append(CentreAlignFormatting("Max UID", 10));
1021 counterHeader.append(" | ");
1022 counterHeader.append(CentreAlignFormatting("Class", 8));
1023 counterHeader.append(" | ");
1024 counterHeader.append(CentreAlignFormatting("Interpolation", 14));
1025 counterHeader.append(" | ");
1026 counterHeader.append(CentreAlignFormatting("Multiplier", 20));
1027 counterHeader.append(" | ");
1028 counterHeader.append(CentreAlignFormatting("Counter set UID", 16));
1029 counterHeader.append(" | ");
1030 counterHeader.append(CentreAlignFormatting("Device UID", 14));
1031 counterHeader.append("\n");
1033 std::cout << "\n" << "\n";
1034 std::cout << CentreAlignFormatting("EVENTS IN CATEGORY: " + category->m_Name,
1035 static_cast<int>(counterHeader.size()));
1037 std::cout << std::string(counterHeader.size(), '=') << "\n";
1038 std::cout << counterHeader;
1039 for (auto& it: category->m_Counters) {
1040 auto search = counterMap.find(it);
1041 if(search != counterMap.end()) {
1042 PrintCounterDetails(search->second);
1047 void PrintCounterDirectory(ICounterDirectory& counterDirectory)
1049 std::string devicesHeader;
1051 devicesHeader.append(CentreAlignFormatting("Device name", 20));
1052 devicesHeader.append(" | ");
1053 devicesHeader.append(CentreAlignFormatting("UID", 13));
1054 devicesHeader.append(" | ");
1055 devicesHeader.append(CentreAlignFormatting("Cores", 10));
1056 devicesHeader.append("\n");
1058 std::cout << "\n" << "\n";
1059 std::cout << CentreAlignFormatting("DEVICES", static_cast<int>(devicesHeader.size()));
1061 std::cout << std::string(devicesHeader.size(), '=') << "\n";
1062 std::cout << devicesHeader;
1063 for (auto& it: counterDirectory.GetDevices()) {
1064 PrintDeviceDetails(it);
1067 std::string counterSetHeader;
1069 counterSetHeader.append(CentreAlignFormatting("Counter set name", 20));
1070 counterSetHeader.append(" | ");
1071 counterSetHeader.append(CentreAlignFormatting("UID", 13));
1072 counterSetHeader.append(" | ");
1073 counterSetHeader.append(CentreAlignFormatting("Count", 10));
1074 counterSetHeader.append("\n");
1076 std::cout << "\n" << "\n";
1077 std::cout << CentreAlignFormatting("COUNTER SETS", static_cast<int>(counterSetHeader.size()));
1079 std::cout << std::string(counterSetHeader.size(), '=') << "\n";
1081 std::cout << counterSetHeader;
1083 for (auto& it: counterDirectory.GetCounterSets()) {
1084 PrintCounterSetDetails(it);
1087 auto counters = counterDirectory.GetCounters();
1088 for (auto& it: counterDirectory.GetCategories()) {
1089 PrintCategoryDetails(it, counters);
1094 uint64_t GetTimestamp()
1096 #if USE_CLOCK_MONOTONIC_RAW
1097 using clock = MonotonicClockRaw;
1099 using clock = std::chrono::steady_clock;
1103 auto timestamp = clock::now();
1105 return static_cast<uint64_t>(timestamp.time_since_epoch().count());
1108 } // namespace profiling
1110 } // namespace armnn
1115 bool operator==(const std::vector<uint8_t>& left, std::thread::id right)
1117 return std::memcmp(left.data(), &right, left.size()) == 0;