add usd-21-11-win64_py39

This commit is contained in:
Sébastien Albert committed 2021-12-07 17:43:55 +01:00
1 parent 41d23e71ba
commit ba5e1f7e67
15684 files changed
+3069957

No files matched your search

+265
View File
@@ -0,0 +1,265 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_AGGREGATE_NODE_H
#define PXR_BASE_TRACE_AGGREGATE_NODE_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/event.h"
#include "pxr/base/trace/threads.h"
#include "pxr/base/tf/refBase.h"
#include "pxr/base/tf/refPtr.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/tf/weakBase.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/base/tf/declarePtrs.h"
#include "pxr/base/arch/timing.h"
#include <vector>
#include "pxr/base/tf/denseHashMap.h"
PXR_NAMESPACE_OPEN_SCOPE
TF_DECLARE_WEAK_AND_REF_PTRS(TraceAggregateNode);
////////////////////////////////////////////////////////////////////////////////
/// \class TraceAggregateNode
///
/// A representation of a call tree. Each node represents one or more calls that
/// occurred in the trace. Multiple calls to a child node are aggregated into one
/// node.
///
class TraceAggregateNode : public TfRefBase, public TfWeakBase {
public:
using This = TraceAggregateNode;
using ThisPtr = TraceAggregateNodePtr;
using ThisRefPtr = TraceAggregateNodeRefPtr;
using TimeStamp = TraceEvent::TimeStamp;
// This class is only used for validity checks.
// FIXME: This class should be removed.
class Id
{
public:
Id() : _valid(false) {}
Id(const TraceThreadId&) : _valid(true) {}
bool IsValid() const { return _valid; }
private:
bool _valid;
};
static ThisRefPtr New() {
return This::New(Id(), TfToken("root"), 0, 0);
}
static ThisRefPtr New(const Id &id,
const TfToken &key,
const TimeStamp ts,
const int count = 1,
const int exclusiveCount = 1) {
return TfCreateRefPtr(new This(id, key, ts, count, exclusiveCount));
}
TRACE_API TraceAggregateNodeRefPtr
Append(Id id, const TfToken &key, TimeStamp ts,
int c = 1, int xc = 1);
TRACE_API void Append(TraceAggregateNodeRefPtr child);
/// Returns the node's key.
TfToken GetKey() { return _key;}
/// Returns the node's id.
const Id &GetId() { return _id;}
/// \name Profile Data Accessors
/// @{
/// Returns the total time of this node ands its children.
TimeStamp GetInclusiveTime() { return _ts; }
/// Returns the time spent in this node but not its children.
TRACE_API TimeStamp GetExclusiveTime(bool recursive = false);
/// Returns the call count of this node. \p recursive determines if
/// recursive calls are counted.
int GetCount(bool recursive = false) const {
return recursive ? _recursiveCount : _count;
}
/// Returns the exclusive count.
int GetExclusiveCount() const { return _exclusiveCount; }
/// @}
/// \name Counter Value Accessors
/// @{
TRACE_API void AppendInclusiveCounterValue(int index, double value);
TRACE_API double GetInclusiveCounterValue(int index) const;
TRACE_API void AppendExclusiveCounterValue(int index, double value);
TRACE_API double GetExclusiveCounterValue(int index) const;
/// @}
/// Recursively calculates the inclusive counter values from the inclusive
/// and exclusive counts of child nodes.
TRACE_API void CalculateInclusiveCounterValues();
/// \name Children Accessors
/// @{
const TraceAggregateNodePtrVector GetChildren() {
// convert to a vector of weak ptrs
return TraceAggregateNodePtrVector( _children.begin(),_children.end() );
}
const TraceAggregateNodeRefPtrVector &GetChildrenRef() {
return _children;
}
TRACE_API TraceAggregateNodeRefPtr GetChild(const TfToken &key);
TraceAggregateNodeRefPtr GetChild(const std::string &key) {
return GetChild(TfToken(key));
}
/// @}
/// Sets whether or not this node is expanded in a gui.
void SetExpanded(bool expanded) {
_expanded = expanded;
}
/// Returns whether this node is expanded in a gui.
bool IsExpanded() {
return _expanded;
}
/// \name Recursion
/// @{
/// Scans the tree for recursive calls and updates the recursive counts.
///
/// This call leaves the tree topology intact, and only updates the
/// recursion-related data in the node. Prior to this call, recursion
/// data is invalid in the node.
TRACE_API void MarkRecursiveChildren();
/// Returns true if this node is simply a marker for a merged recursive
/// subtree; otherwise returns false.
///
/// This value is meaningless until this node or any of its ancestors have
/// been marked with MarkRecursiveChildren().
bool IsRecursionMarker() const { return _isRecursionMarker; }
/// Returns true if this node is the head of a recursive call tree
/// (i.e. the function has been called recursively).
///
/// This value is meaningless until this node or any of its ancestors have
/// been marked with MarkRecursiveChildren().
bool IsRecursionHead() const { return _isRecursionHead; }
/// @}
private:
TraceAggregateNode(const Id &id, const TfToken &key, TimeStamp ts,
int count, int exclusiveCount) :
_id(id), _key(key), _ts(ts), _exclusiveTs(ts),
_count(count), _exclusiveCount(exclusiveCount),
_recursiveCount(count), _recursiveExclusiveTs(ts), _expanded(false),
_isRecursionMarker(false), _isRecursionHead(false),
_isRecursionProcessed(false) {}
using _ChildDictionary = TfDenseHashMap<TfToken, size_t, TfHash>;
void _MergeRecursive(const TraceAggregateNodeRefPtr &node);
void _SetAsRecursionMarker(TraceAggregateNodePtr parent);
Id _id;
TfToken _key;
TimeStamp _ts;
TimeStamp _exclusiveTs;
int _count;
int _exclusiveCount;
// We keep the recursive counts separate so that we don't mess with
// the collected data.
int _recursiveCount;
TraceAggregateNodePtr _recursionParent;
TimeStamp _recursiveExclusiveTs;
TraceAggregateNodeRefPtrVector _children;
_ChildDictionary _childrenByKey;
// A structure that holds on to the inclusive and exclusive counter
// values. These values are usually populated together, so it's beneficial
// to maintain them in a tightly packed structure.
struct _CounterValue {
_CounterValue() : inclusive(0.0), exclusive(0.0) {}
double inclusive;
double exclusive;
};
using _CounterValues = TfDenseHashMap<int, _CounterValue, TfHash>;
// The counter values associated with specific counter indices
_CounterValues _counterValues;
unsigned int
// If multiple Trace Editors are to be pointed at the same Reporter, this
// might have to be changed
_expanded:1,
// This flag keeps track of whether or not this node is simply intended
// as a marker for the start of a recursive call tree.
_isRecursionMarker:1,
// This flag keeps track of whether or not a node is the head of a
// recursive call tree. In other words, if it is a function that has been
// called recursively.
_isRecursionHead:1,
// This flag is used during recursive traversal to mark the node as having
// been visited and avoid too much processing.
_isRecursionProcessed:1;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_AGGREGATE_NODE_H
+109
View File
@@ -0,0 +1,109 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_AGGREGATE_TREE_H
#define PXR_BASE_TRACE_AGGREGATE_TREE_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/aggregateNode.h"
PXR_NAMESPACE_OPEN_SCOPE
class TraceCollection;
TF_DECLARE_WEAK_AND_REF_PTRS(TraceAggregateTree);
TF_DECLARE_WEAK_AND_REF_PTRS(TraceEventTree);
////////////////////////////////////////////////////////////////////////////////
/// \class TraceAggregateTree
///
/// A representation of a call tree. Each node represents one or more calls that
/// occurred in the trace. Multiple calls to a child node are aggregated into one
/// node.
///
class TraceAggregateTree : public TfRefBase, public TfWeakBase {
public:
using This = TraceAggregateTree;
using ThisPtr = TraceAggregateTreePtr;
using ThisRefPtr = TraceAggregateTreeRefPtr;
using TimeStamp = TraceEvent::TimeStamp;
using EventTimes = std::map<TfToken, TimeStamp>;
using CounterMap = TfHashMap<TfToken, double, TfToken::HashFunctor>;
/// Create an empty tree
static ThisRefPtr New() {
return TfCreateRefPtr(new This());
}
/// Returns the root node of the tree.
TraceAggregateNodePtr GetRoot() { return _root; }
/// Returns a map of event keys to total inclusive time.
const EventTimes& GetEventTimes() const { return _eventTimes; }
/// Returns a map of counters (counter keys), associated with their total
/// accumulated value. Each individual event node in the tree may also hold
/// on to an inclusive and exclusive value for the given counter.
const CounterMap& GetCounters() const { return _counters; }
/// Returns the numeric index associated with a counter key. Counter values
/// on the event nodes will have to be looked up by the numeric index.
TRACE_API int GetCounterIndex(const TfToken &key) const;
/// Add a counter to the tree. This method can be used to restore a
/// previous trace state and tree. Note, that the counter being added must
/// have a unique key and index. The method will return false if a key or
/// index already exists.
TRACE_API bool AddCounter(const TfToken &key, int index, double totalValue);
/// Removes all data and nodes from the tree.
TRACE_API void Clear();
/// Creates new nodes and counter data from data in \p eventTree and \p
/// collection.
TRACE_API void Append(
const TraceEventTreeRefPtr& eventTree,
const TraceCollection& collection);
private:
TRACE_API TraceAggregateTree();
using _CounterIndexMap =TfHashMap<TfToken, int, TfToken::HashFunctor>;
TraceAggregateNodeRefPtr _root;
EventTimes _eventTimes;
CounterMap _counters;
_CounterIndexMap _counterIndexMap;
int _counterIndex;
friend class Trace_AggregateTreeBuilder;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_AGGREGATE_TREE_H
+47
View File
@@ -0,0 +1,47 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_API_H
#define PXR_BASE_TRACE_API_H
#include "pxr/base/arch/export.h"
#if defined(PXR_STATIC)
# define TRACE_API
# define TRACE_API_TEMPLATE_CLASS(...)
# define TRACE_API_TEMPLATE_STRUCT(...)
# define TRACE_LOCAL
#else
# if defined(TRACE_EXPORTS)
# define TRACE_API ARCH_EXPORT
# define TRACE_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__)
# define TRACE_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__)
# else
# define TRACE_API ARCH_IMPORT
# define TRACE_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__)
# define TRACE_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__)
# endif
# define TRACE_LOCAL ARCH_HIDDEN
#endif
#endif // PXR_BASE_TRACE_API_H
+90
View File
@@ -0,0 +1,90 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_CATEGORY_H
#define PXR_BASE_TRACE_CATEGORY_H
/// \file trace/category.h
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/tf/singleton.h"
#include "pxr/base/trace/stringHash.h"
#include <cstdint>
#include <map>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// Categories that a TraceReporter can use to filter events.
using TraceCategoryId = uint32_t;
///////////////////////////////////////////////////////////////////////////////
///
/// \class TraceCategory
///
/// This singleton class provides a way to mark TraceEvent instances with
/// category Ids which can be used to filter them. This class also provides a
/// way to associate TraceCategoryId values with human readable names.
///
class TraceCategory {
public:
/// Computes an id for the given a string literal \p str.
template <int N>
static constexpr TraceCategoryId CreateTraceCategoryId(
const char (&str)[N]) {
return TraceStringHash::Hash(str);
}
/// Default category if none are explicitly specified when creating a
/// TraceEvent.
enum : TraceCategoryId { Default = 0 };
/// Associates the \p id with \p name. These associates are not necessarily
/// unique.
TRACE_API void RegisterCategory(TraceCategoryId id, const std::string& name);
/// Returns all names associated with the \p id.
TRACE_API std::vector<std::string> GetCategories(TraceCategoryId id) const;
/// Singleton accessor.
TRACE_API static TraceCategory& GetInstance();
private:
friend class TfSingleton<TraceCategory>;
TraceCategory();
// Mapping of ids to names.
std::multimap<TraceCategoryId, std::string> _idToNames;
};
TRACE_API_TEMPLATE_CLASS(TfSingleton<TraceCategory>);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_CATEGORY_H
+143
View File
@@ -0,0 +1,143 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_COLLECTION_H
#define PXR_BASE_TRACE_COLLECTION_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/event.h"
#include "pxr/base/trace/eventList.h"
#include "pxr/base/trace/threads.h"
#include "pxr/base/tf/mallocTag.h"
#include <map>
#include <unordered_map>
PXR_NAMESPACE_OPEN_SCOPE
///////////////////////////////////////////////////////////////////////////////
///
/// \class TraceCollection
///
/// This class owns lists of TraceEvent instances per thread, and allows
/// read access to them.
///
class TraceCollection {
public:
TF_MALLOC_TAG_NEW("Trace", "TraceCollection");
using This = TraceCollection;
using EventList = TraceEventList;
using EventListPtr = std::unique_ptr<EventList>;
/// Constructor.
TraceCollection() = default;
/// Move constructor.
TraceCollection(TraceCollection&&) = default;
/// Move assignment operator.
TraceCollection& operator=(TraceCollection&&) = default;
// Collections should not be copied because TraceEvents contain
// pointers to elements in the Key cache.
TraceCollection(const TraceCollection&) = delete;
TraceCollection& operator=(const TraceCollection&) = delete;
/// Appends \p events to the collection. The collection will
/// take ownership of the data.
TRACE_API void AddToCollection(const TraceThreadId& id, EventListPtr&& events);
////////////////////////////////////////////////////////////////////////
///
/// \class Visitor
///
/// This interface provides a way to access data a TraceCollection.
///
class Visitor {
public:
/// Destructor
TRACE_API virtual ~Visitor();
/// Called at the beginning of an iteration.
virtual void OnBeginCollection() = 0;
/// Called at the end of an iteration.
virtual void OnEndCollection() = 0;
/// Called before the first event of from the thread with
/// \p threadId is encountered.
virtual void OnBeginThread(const TraceThreadId& threadId) = 0;
/// Called after the last event of from the thread with
/// \p threadId is encountered.
virtual void OnEndThread(const TraceThreadId& threadId) = 0;
/// Called before an event with \p categoryId is visited. If the
/// return value is false, the event will be visited.
virtual bool AcceptsCategory(TraceCategoryId categoryId) = 0;
/// Called for every event \p event with \p key on thread
/// \p threadId if AcceptsCategory returns true.
virtual void OnEvent(
const TraceThreadId& threadId,
const TfToken& key,
const TraceEvent& event) = 0;
};
/// Forward iterates over the events of the collection and calls the
/// \p visitor callbacks.
TRACE_API void Iterate(Visitor& visitor) const;
/// Reverse iterates over the events of the collection and calls the
/// \p visitor callbacks.
TRACE_API void ReverseIterate(Visitor& visitor) const;
private:
using KeyTokenCache =
std::unordered_map<TraceKey, TfToken, TraceKey::HashFunctor>;
/// Iterate through threads, then choose either forward or reverse
/// iteration for the events in the threads
void _Iterate(Visitor& visitor, bool doReverse) const;
// Iterate through events in either forward or reverse order, depending on
// the templated arguments
template <class I>
void _IterateEvents(Visitor&, KeyTokenCache&,
const TraceThreadId&, I, I) const;
using EventTable = std::map<TraceThreadId, EventListPtr>;
EventTable _eventsPerThread;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_COLLECTION_H
+64
View File
@@ -0,0 +1,64 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_COLLECTION_NOTICE_H
#define PXR_BASE_TRACE_COLLECTION_NOTICE_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/tf/notice.h"
#include "pxr/base/trace/collection.h"
PXR_NAMESPACE_OPEN_SCOPE
///////////////////////////////////////////////////////////////////////////////
/// \class TraceCollectionAvailable
///
/// A TfNotice that is sent when the TraceCollector creates a TraceCollection.
/// This can potentially be sent from multiple threads. Listeners must be
/// thread safe.
class TraceCollectionAvailable : public TfNotice
{
public:
/// Constructor.
TraceCollectionAvailable(const std::shared_ptr<TraceCollection>& collection)
: _collection(collection)
{}
/// Destructor.
TRACE_API virtual ~TraceCollectionAvailable();
/// Returns the TraceCollection which was produced.
const std::shared_ptr<TraceCollection>& GetCollection() const {
return _collection;
}
private:
std::shared_ptr<TraceCollection> _collection;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_COLLECTION_NOTICE_H
+620
View File
@@ -0,0 +1,620 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_COLLECTOR_H
#define PXR_BASE_TRACE_COLLECTOR_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/concurrentList.h"
#include "pxr/base/trace/collection.h"
#include "pxr/base/trace/event.h"
#include "pxr/base/trace/key.h"
#include "pxr/base/trace/threads.h"
#include "pxr/base/tf/declarePtrs.h"
#include "pxr/base/tf/mallocTag.h"
#ifdef PXR_PYTHON_SUPPORT_ENABLED
#include "pxr/base/tf/pyTracing.h"
#endif // PXR_PYTHON_SUPPORT_ENABLED
#include "pxr/base/tf/singleton.h"
#include "pxr/base/tf/refBase.h"
#include "pxr/base/tf/refPtr.h"
#include "pxr/base/tf/weakBase.h"
#include "pxr/base/tf/weakPtr.h"
#include <atomic>
#include <string>
#include <vector>
#include <tbb/spin_mutex.h>
PXR_NAMESPACE_OPEN_SCOPE
class TraceScopeHolder;
TF_DECLARE_WEAK_PTRS(TraceCollector);
TF_DECLARE_WEAK_AND_REF_PTRS(TraceScope);
////////////////////////////////////////////////////////////////////////////////
/// \class TraceCollector
///
/// This is a singleton class that records TraceEvent instances and populates
/// TraceCollection instances.
///
/// All public methods of TraceCollector are safe to call from any thread.
class TraceCollector : public TfWeakBase {
public:
TF_MALLOC_TAG_NEW("Trace", "TraceCollector");
using This = TraceCollector;
using ThisPtr = TraceCollectorPtr;
using TimeStamp = TraceEvent::TimeStamp;
using Key = TraceDynamicKey;
/// Returns the singleton instance.
TRACE_API static TraceCollector& GetInstance() {
return TfSingleton<TraceCollector>::GetInstance();
}
TRACE_API ~TraceCollector();
/// Enables or disables collection of events for DefaultCategory.
TRACE_API void SetEnabled(bool isEnabled);
/// Returns whether collection of events is enabled for DefaultCategory.
static bool IsEnabled() {
return (_isEnabled.load(std::memory_order_acquire) == 1);
}
/// Default Trace category which corresponds to events stored for TRACE_
/// macros.
struct DefaultCategory {
/// Returns TraceCategory::Default.
static constexpr TraceCategoryId GetId() { return TraceCategory::Default;}
/// Returns the result of TraceCollector::IsEnabled.
static bool IsEnabled() { return TraceCollector::IsEnabled(); }
};
#ifdef PXR_PYTHON_SUPPORT_ENABLED
/// Returns whether automatic tracing of all python scopes is enabled.
bool IsPythonTracingEnabled() const {
return _isPythonTracingEnabled.load(std::memory_order_acquire) != 0;
}
/// Set whether automatic tracing of all python scopes is enabled.
TRACE_API void SetPythonTracingEnabled(bool enabled);
#endif // PXR_PYTHON_SUPPORT_ENABLED
/// Clear all pending events from the collector. No TraceCollection will be
/// made for these events.
TRACE_API void Clear();
/// \name Event Recording
/// @{
/// Record a begin event with \a key if \p Category is enabled.
/// A matching end event is expected some time in the future.
///
/// If the key is known at compile time \c BeginScope and \c Scope methods
/// are preferred because they have lower overhead.
/// \returns The TimeStamp of the TraceEvent or 0 if the collector is
/// disabled.
/// \sa BeginScope \sa Scope
template <typename Category = DefaultCategory>
TimeStamp BeginEvent(const Key& key) {
if (ARCH_LIKELY(!Category::IsEnabled())) {
return 0;
}
return _BeginEvent(key, Category::GetId());
}
/// Record a begin event with \a key at a specified time if \p Category is
/// enabled.
/// This version of the method allows the passing of a specific number of
/// elapsed milliseconds, \a ms, to use for this event.
/// This method is used for testing and debugging code.
template <typename Category = DefaultCategory>
void BeginEventAtTime(const Key& key, double ms) {
if (ARCH_LIKELY(!Category::IsEnabled())) {
return;
}
_BeginEventAtTime(key, ms, Category::GetId());
}
/// Record an end event with \a key if \p Category is enabled.
/// A matching begin event must have preceded this end event.
///
/// If the key is known at compile time EndScope and Scope methods are
/// preferred because they have lower overhead.
/// \returns The TimeStamp of the TraceEvent or 0 if the collector is
/// disabled.
/// \sa EndScope \sa Scope
template <typename Category = DefaultCategory>
TimeStamp EndEvent(const Key& key) {
if (ARCH_LIKELY(!Category::IsEnabled())) {
return 0;
}
return _EndEvent(key, Category::GetId());
}
/// Record an end event with \a key at a specified time if \p Category is
/// enabled.
/// This version of the method allows the passing of a specific number of
/// elapsed milliseconds, \a ms, to use for this event.
/// This method is used for testing and debugging code.
template <typename Category = DefaultCategory>
void EndEventAtTime(const Key& key, double ms) {
if (ARCH_LIKELY(!Category::IsEnabled())) {
return;
}
_EndEventAtTime(key, ms, Category::GetId());
}
/// Record a marker event with \a key if \p Category is enabled.
/// Unlike begin/end, there is no matching event for marker events
///
template <typename Category = DefaultCategory>
TimeStamp MarkerEvent(const Key& key) {
if (ARCH_LIKELY(!Category::IsEnabled())) {
return 0;
}
return _MarkerEvent(key, Category::GetId());
}
/// Record a marker event with \a key at a specified time if \p Category is
/// enabled.
/// This version of the method allows the passing of a specific number of
/// elapsed milliseconds, \a ms, to use for this event.
/// This method is used for testing and debugging code.
template <typename Category = DefaultCategory>
void MarkerEventAtTime(const Key& key, double ms) {
if (ARCH_LIKELY(!Category::IsEnabled())) {
return;
}
_MarkerEventAtTime(key, ms, Category::GetId());
}
/// Record a begin event for a scope described by \a key if \p Category is
/// enabled.
/// It is more efficient to use the \c Scope method than to call both
/// \c BeginScope and \c EndScope.
/// \sa EndScope \sa Scope
template <typename Category = DefaultCategory>
void BeginScope(const TraceKey& _key) {
if (ARCH_LIKELY(!Category::IsEnabled()))
return;
_BeginScope(_key, Category::GetId());
}
/// Record a begin event for a scope described by \a key and a specified
/// category and store data arguments if \p Category is enabled.
/// The variadic arguments \a args must be an even number of parameters in
/// the form TraceKey, Value.
/// \sa EndScope \sa Scope \sa StoreData
template <typename Category, typename... Args>
void BeginScope(
const TraceKey& key, Args&&... args) {
static_assert( sizeof...(Args) %2 == 0,
"Data arguments must come in pairs");
if (ARCH_LIKELY(!Category::IsEnabled()))
return;
_PerThreadData *threadData = _GetThreadData();
threadData->BeginScope(key, Category::GetId());
_StoreDataRec(threadData, Category::GetId(), std::forward<Args>(args)...);
}
/// Record a begin event for a scope described by \a key and store data
/// arguments if \p Category is enabled. The variadic arguments \a args must
/// be an even number of parameters in the form TraceKey, Value.
/// \sa EndScope \sa Scope \sa StoreData
template <typename... Args>
void BeginScope(const TraceKey& key, Args&&... args) {
static_assert( sizeof...(Args) %2 == 0,
"Data arguments must come in pairs");
// Explicitly cast to TraceCategoryId so overload resolution choose the
// version with a category arguement.
BeginScope<DefaultCategory>(key,
std::forward<Args>(args)...);
}
/// Record an end event described by \a key if \p Category is enabled.
/// It is more efficient to use the \c Scope method than to call both
/// \c BeginScope and \c EndScope.
/// \sa BeginScope \sa Scope
template <typename Category = DefaultCategory>
void EndScope(const TraceKey& key) {
if (ARCH_LIKELY(!Category::IsEnabled()))
return;
_EndScope(key, Category::GetId());
}
/// Record a scope event described by \a key that started at \a start if
/// \p Category is enabled.
///
/// This method is used by the TRACE_FUNCTION, TRACE_SCOPE and
/// TRACE_FUNCTION_SCOPE macros.
/// \sa BeginScope \sa EndScope
template <typename Category = DefaultCategory>
void Scope(const TraceKey& key, TimeStamp start) {
if (ARCH_LIKELY(!Category::IsEnabled()))
return;
_PerThreadData *threadData = _GetThreadData();
threadData->EmplaceEvent(
TraceEvent::Timespan, key, start, Category::GetId());
}
/// Record multiple data events with category \a cat if \p Category is
/// enabled.
/// \sa StoreData
template <typename Category, typename... Args>
void ScopeArgs(Args&&... args) {
static_assert( sizeof...(Args) %2 == 0,
"Data arguments must come in pairs");
if (ARCH_LIKELY(!Category::IsEnabled()))
return;
_PerThreadData *threadData = _GetThreadData();
_StoreDataRec(threadData, Category::GetId(), std::forward<Args>(args)...);
}
/// Record multiple data events with the default category if collection of
/// events is enabled.
/// The variadic arguments \a args must be an even number of parameters in
/// the form TraceKey, Value. It is more efficient to use this method to
/// store multiple data items than to use multiple calls to \c StoreData.
/// \sa StoreData
template <typename... Args>
void ScopeArgs(Args&&... args) {
static_assert( sizeof...(Args) %2 == 0,
"Data arguments must come in pairs");
ScopeArgs<DefaultCategory>(std::forward<Args>(args)...);
}
/// Record a scope event described by \a key that started at \a start if
/// \p Category is enabled.
///
/// This method is used by the TRACE_FUNCTION, TRACE_SCOPE and
/// TRACE_FUNCTION_SCOPE macros.
/// \sa BeginScope \sa EndScope
template <typename Category = DefaultCategory>
void MarkerEventStatic(const TraceKey& key) {
if (ARCH_LIKELY(!Category::IsEnabled()))
return;
_PerThreadData *threadData = _GetThreadData();
threadData->EmplaceEvent(
TraceEvent::Marker, key, Category::GetId());
}
/// Record a data event with the given \a key and \a value if \p Category is
/// enabled. \a value may be of any type which a TraceEvent can
/// be constructed from (bool, int, std::string, uint64, double).
/// \sa ScopeArgs
template <typename Category = DefaultCategory, typename T>
void StoreData(const TraceKey &key, const T& value) {
if (ARCH_UNLIKELY(Category::IsEnabled())) {
_StoreData(_GetThreadData(), key, Category::GetId(), value);
}
}
/// Record a counter \a delta for a name \a key if \p Category is enabled.
template <typename Category = DefaultCategory>
void RecordCounterDelta(const TraceKey &key,
double delta) {
// Only record counter values if the collector is enabled.
if (ARCH_UNLIKELY(Category::IsEnabled())) {
_PerThreadData *threadData = _GetThreadData();
threadData->EmplaceEvent(
TraceEvent::CounterDelta, key, delta, Category::GetId());
}
}
/// Record a counter \a delta for a name \a key if \p Category is enabled.
template <typename Category = DefaultCategory>
void RecordCounterDelta(const Key &key, double delta) {
if (ARCH_UNLIKELY(Category::IsEnabled())) {
_PerThreadData *threadData = _GetThreadData();
threadData->CounterDelta(key, delta, Category::GetId());
}
}
/// Record a counter \a value for a name \a key if \p Category is enabled.
template <typename Category = DefaultCategory>
void RecordCounterValue(const TraceKey &key, double value) {
// Only record counter values if the collector is enabled.
if (ARCH_UNLIKELY(Category::IsEnabled())) {
_PerThreadData *threadData = _GetThreadData();
threadData->EmplaceEvent(
TraceEvent::CounterValue, key, value, Category::GetId());
}
}
/// Record a counter \a value for a name \a key and delta \a value if
/// \p Category is enabled.
template <typename Category = DefaultCategory>
void RecordCounterValue(const Key &key, double value) {
if (ARCH_UNLIKELY(Category::IsEnabled())) {
_PerThreadData *threadData = _GetThreadData();
threadData->CounterValue(key, value, Category::GetId());
}
}
/// @}
/// Return the label associated with this collector.
const std::string& GetLabel() {
return _label;
}
/// Produces a TraceCollection from all the events that recorded in the
/// collector and issues a TraceCollectionAvailable notice. Note that
/// creating a collection restarts tracing, i.e. events contained in this
/// collection will not be present in subsequent collections.
TRACE_API void CreateCollection();
private:
TraceCollector();
friend class TfSingleton<TraceCollector>;
class _PerThreadData;
// Return a pointer to existing per-thread data or create one if none
// exists.
TRACE_API _PerThreadData* _GetThreadData();
TRACE_API TimeStamp _BeginEvent(const Key& key, TraceCategoryId cat);
TRACE_API void _BeginEventAtTime(
const Key& key, double ms, TraceCategoryId cat);
TRACE_API TimeStamp _EndEvent(const Key& key, TraceCategoryId cat);
TRACE_API void _EndEventAtTime(
const Key& key, double ms, TraceCategoryId cat);
TRACE_API TimeStamp _MarkerEvent(const Key& key, TraceCategoryId cat);
TRACE_API void _MarkerEventAtTime(
const Key& key, double ms, TraceCategoryId cat);
// This is the fast execution path called from the TRACE_FUNCTION
// and TRACE_SCOPE macros
void _BeginScope(const TraceKey& key, TraceCategoryId cat)
{
// Note we're not calling _NewEvent, don't need to cache key
_PerThreadData *threadData = _GetThreadData();
threadData->BeginScope(key, cat);
}
// This is the fast execution path called from the TRACE_FUNCTION
// and TRACE_SCOPE macros
TRACE_API void _EndScope(const TraceKey& key, TraceCategoryId cat);
#ifdef PXR_PYTHON_SUPPORT_ENABLED
// Callback function registered as a python tracing function.
void _PyTracingCallback(const TfPyTraceInfo &info);
#endif // PXR_PYTHON_SUPPORT_ENABLED
// Implementation for small data that can stored inlined with the event.
template <typename T,
typename std::enable_if<
sizeof(T) <= sizeof(uintptr_t)
&& !std::is_pointer<T>::value , int>::type = 0>
void _StoreData(_PerThreadData* threadData, const TraceKey &key,
TraceCategoryId cat, const T& value) {
threadData->StoreData(key, value, cat);
}
// Implementation for data that must be stored outside of the events.
template <typename T,
typename std::enable_if<
(sizeof(T) > sizeof(uintptr_t))
&& !std::is_pointer<T>::value, int>::type = 0>
void _StoreData(_PerThreadData* threadData, const TraceKey &key,
TraceCategoryId cat, const T& value) {
threadData->StoreLargeData(key, value, cat);
}
// Specialization for c string
void _StoreData(
_PerThreadData* threadData,
const TraceKey &key,
TraceCategoryId cat,
const char* value) {
threadData->StoreLargeData(key, value, cat);
}
// Specialization for std::string
void _StoreData(
_PerThreadData* threadData,
const TraceKey &key,
TraceCategoryId cat,
const std::string& value) {
threadData->StoreLargeData(key, value.c_str(), cat);
}
// Variadic version to store multiple data events in one function call.
template <typename K, typename T, typename... Args>
void _StoreDataRec(
_PerThreadData* threadData, TraceCategoryId cat, K&& key,
const T& value, Args&&... args) {
_StoreData(threadData, std::forward<K>(key), cat, value);
_StoreDataRec(threadData, cat, std::forward<Args>(args)...);
}
// Base case to terminate template recursion
void _StoreDataRec(_PerThreadData* threadData, TraceCategoryId cat) {}
// Thread-local storage, accessed via _GetThreadData()
//
class _PerThreadData {
public:
using EventList = TraceCollection::EventList;
_PerThreadData();
~_PerThreadData();
const TraceThreadId& GetThreadId() const {
return _threadIndex;
}
TimeStamp BeginEvent(const Key& key, TraceCategoryId cat);
TimeStamp EndEvent(const Key& key, TraceCategoryId cat);
TimeStamp MarkerEvent(const Key& key, TraceCategoryId cat);
// Debug Methods
void BeginEventAtTime(
const Key& key, double ms, TraceCategoryId cat);
void EndEventAtTime(const Key& key, double ms, TraceCategoryId cat);
void MarkerEventAtTime(const Key& key, double ms, TraceCategoryId cat);
void BeginScope(const TraceKey& key, TraceCategoryId cat) {
AtomicRef lock(_writing);
_BeginScope(key, cat);
}
void EndScope(const TraceKey& key, TraceCategoryId cat) {
AtomicRef lock(_writing);
_EndScope(key, cat);
}
TRACE_API void CounterDelta(
const Key&, double value, TraceCategoryId cat);
TRACE_API void CounterValue(
const Key&, double value, TraceCategoryId cat);
template <typename T>
void StoreData(
const TraceKey& key, const T& data, TraceCategoryId cat) {
AtomicRef lock(_writing);
_events.load(std::memory_order_acquire)->EmplaceBack(
TraceEvent::Data, key, data, cat);
}
template <typename T>
void StoreLargeData(
const TraceKey& key, const T& data, TraceCategoryId cat) {
AtomicRef lock(_writing);
EventList* events = _events.load(std::memory_order_acquire);
const auto* cached = events->StoreData(data);
events->EmplaceBack(TraceEvent::Data, key, cached, cat);
}
template <typename... Args>
void EmplaceEvent(Args&&... args) {
AtomicRef lock(_writing);
_events.load(std::memory_order_acquire)->EmplaceBack(
std::forward<Args>(args)...);
}
#ifdef PXR_PYTHON_SUPPORT_ENABLED
void PushPyScope(const Key& key, bool enabled);
void PopPyScope(bool enabled);
#endif // PXR_PYTHON_SUPPORT_ENABLED
// These methods can be called from threads at the same time as the
// other methods.
std::unique_ptr<EventList> GetCollectionData();
void Clear();
private:
void _BeginScope(const TraceKey& key, TraceCategoryId cat) {
_events.load(std::memory_order_acquire)->EmplaceBack(
TraceEvent::Begin, key, cat);
}
void _EndScope(const TraceKey& key, TraceCategoryId cat);
// Flag to let other threads know that the list is being written to.
mutable std::atomic<bool> _writing;
std::atomic<EventList*> _events;
class AtomicRef {
public:
AtomicRef(std::atomic<bool>& b) : _bool(b) {
_bool.store(true, std::memory_order_release);
}
~AtomicRef() {
_bool.store(false, std::memory_order_release);
}
private:
std::atomic<bool>& _bool;
};
// An integer that is unique for each thread launched by any
// threadDispatcher. Each time a thread is Start-ed it get's
// a new id.
//
TraceThreadId _threadIndex;
#ifdef PXR_PYTHON_SUPPORT_ENABLED
// When auto-tracing python frames, this stores the stack of scopes.
struct PyScope {
Key key;
};
std::vector<PyScope> _pyScopes;
#endif // PXR_PYTHON_SUPPORT_ENABLED
};
TRACE_API static std::atomic<int> _isEnabled;
// A list with one _PerThreadData per thread.
TraceConcurrentList<_PerThreadData> _allPerThreadData;
std::string _label;
#ifdef PXR_PYTHON_SUPPORT_ENABLED
std::atomic<int> _isPythonTracingEnabled;
TfPyTraceFnId _pyTraceFnId;
#endif // PXR_PYTHON_SUPPORT_ENABLED
};
TRACE_API_TEMPLATE_CLASS(TfSingleton<TraceCollector>);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_COLLECTOR_H
+149
View File
@@ -0,0 +1,149 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_CONCURRENT_LIST_H
#define PXR_BASE_TRACE_CONCURRENT_LIST_H
#include "pxr/pxr.h"
#include "pxr/base/arch/align.h"
#include <tbb/cache_aligned_allocator.h>
#include <atomic>
#include <iterator>
PXR_NAMESPACE_OPEN_SCOPE
////////////////////////////////////////////////////////////////////////////////
/// \class TraceConcurrentList
///
/// This class supports thread safe insertion and iteration over a list of items.
///
template <typename T>
class TraceConcurrentList {
// Linked list node that is cache line aligned to prevent false sharing.
struct alignas(ARCH_CACHE_LINE_SIZE*2) Node {
T value;
Node* next;
};
public:
////////////////////////////////////////////////////////////////////////////
/// \class iterator
///
/// This class provides forward iterator support to iterate over all the
/// items.
///
class iterator {
public:
// iterator types
using iterator_category = std::forward_iterator_tag;
using value = T;
using pointer = T*;
using reference = T&;
using difference_type = ptrdiff_t;
iterator() : _node(nullptr) {}
pointer operator->() {
return _node ? &_node->value : nullptr;
}
reference operator*() {
return _node->value;
}
iterator& operator++() {
_node = _node->next;
return *this;
}
iterator operator++(int) {
iterator result(*this);
_node = _node->next;
return result;
}
bool operator !=(const iterator& other) const {
return _node != other._node;
}
bool operator ==(const iterator& other) const {
return _node == other._node;
}
private:
explicit iterator(Node* node) : _node(node) {}
Node* _node;
friend class TraceConcurrentList;
};
/// Constructor.
TraceConcurrentList() : _head(nullptr) {}
/// Destructor.
~TraceConcurrentList() {
// Delete all nodes in the list.
Node* curNode = _head.load(std::memory_order_acquire);
while (curNode) {
Node* nodeToDelete = curNode;
curNode = curNode->next;
_alloc.destroy(nodeToDelete);
_alloc.deallocate(nodeToDelete, 1);
}
}
// No copies
TraceConcurrentList(const TraceConcurrentList&) = delete;
TraceConcurrentList& operator=(const TraceConcurrentList&) = delete;
/// \name Iterator support.
/// @{
iterator begin() { return iterator(_head.load(std::memory_order_acquire)); }
iterator end() { return iterator(); }
/// @}
/// Inserts an item at the beginning of the list and returns an iterator to
/// the newly created item.
iterator Insert() {
Node* newNode = _alloc.allocate(1);
_alloc.construct(newNode);
// Add the node to the linked list in an atomic manner.
do {
newNode->next = _head.load(std::memory_order_relaxed);
} while (!_head.compare_exchange_weak(newNode->next, newNode));
return iterator(newNode);
}
private:
std::atomic<Node*> _head;
tbb::cache_aligned_allocator<Node> _alloc;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_CONCURRENT_LIST_H
+108
View File
@@ -0,0 +1,108 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_COUNTER_ACCUMULATOR_H
#define PXR_BASE_TRACE_COUNTER_ACCUMULATOR_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/collection.h"
#include "pxr/base/tf/token.h"
#include <map>
#include <unordered_map>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
////////////////////////////////////////////////////////////////////////////////
/// \class TraceCounterAccumulator
///
/// This class accumulates counter values from TraceCollection instances.
/// A TraceCounterAccumulator instance can accumulate counters from multiple
/// collections or the state of the counters can be set explicitly through
/// SetCurrentValues().
///
///
class TraceCounterAccumulator : private TraceCollection::Visitor {
public:
using CounterValues = std::vector<std::pair<TraceEvent::TimeStamp, double>>;
using CounterValuesMap =
std::unordered_map<TfToken, CounterValues, TfToken::HashFunctor>;
using CounterMap =
std::unordered_map<TfToken, double, TfToken::HashFunctor>;
/// Constructor.
TraceCounterAccumulator() = default;
/// Returns a map of the counter values over time.
const CounterValuesMap& GetCounters() const {
return _counterValuesOverTime;
}
/// Sets the current value of the counters.
TRACE_API void SetCurrentValues(const CounterMap&);
/// Returns the current value of the counters.
const CounterMap& GetCurrentValues() const {
return _currentValues;
}
/// Reads events /p collection and updates the current values of the
/// counters.
TRACE_API void Update(const TraceCollection& collection);
protected:
/// Determines whether or not counter events with \p id should be processed.
virtual bool _AcceptsCategory(TraceCategoryId id) = 0;
private:
// TraceCollection::Visitor Interface
virtual void OnBeginCollection() override;
virtual void OnEndCollection() override;
virtual void OnBeginThread(const TraceThreadId&) override;
virtual void OnEndThread(const TraceThreadId&) override;
virtual bool AcceptsCategory(TraceCategoryId) override;
virtual void OnEvent(
const TraceThreadId&, const TfToken&, const TraceEvent&) override;
struct _CounterValue {
double value;
bool isDelta;
};
using _CounterDeltaValues =
std::multimap<TraceEvent::TimeStamp, _CounterValue>;
using _CounterDeltaMap = std::map<TfToken, _CounterDeltaValues>;
_CounterDeltaMap _counterDeltas;
CounterValuesMap _counterValuesOverTime;
CounterMap _currentValues;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif //PXR_BASE_TRACE_COUNTER_ACCUMULATOR_H
+129
View File
@@ -0,0 +1,129 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_DATA_BUFFER_H
#define PXR_BASE_TRACE_DATA_BUFFER_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/arch/hints.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <deque>
#include <memory>
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
///////////////////////////////////////////////////////////////////////////////
/// \class TraceDataBuffer
///
/// This class stores copies of data that are associated with TraceEvent
/// instances.
/// Data stored in the buffer must be copy constructible and trivially
/// destructible.
///
class TraceDataBuffer {
public:
constexpr static size_t DefaultAllocSize = 1024;
/// Constructor. The buffer will make allocations of \p allocSize.
///
TraceDataBuffer(size_t allocSize = DefaultAllocSize) : _alloc(allocSize) {}
/// Makes a copy of \p value and returns a pointer to it.
///
template <typename T>
const T* StoreData(const T& value)
{
static_assert(std::is_copy_constructible<T>::value,
"Must by copy constructible");
static_assert(std::is_trivially_destructible<T>::value,
"No destructors will be called");
return new(_alloc.Allocate(alignof(T), sizeof(T))) T(value);
}
/// Makes a copy of \p str and returns a pointer to it.
/// Specialization for c strings.
const char* StoreData(const char* str) {
const size_t strLen = std::strlen(str) + 1;
void* mem = _alloc.Allocate(alignof(char), strLen);
char* cstr = reinterpret_cast<char*>(mem);
std::memcpy(cstr, str, strLen);
return cstr;
}
private:
// Simple Allocator that only supports allocations, but not frees.
// Allocated memory is tied to the lifetime of the allocator object.
class Allocator {
public:
Allocator(size_t blockSize)
: _desiredBlockSize(blockSize) {}
Allocator(Allocator&&) = default;
Allocator& operator=(Allocator&&) = default;
Allocator(const Allocator&) = delete;
Allocator& operator=(const Allocator&) = delete;
void* Allocate(const size_t align, const size_t size) {
Byte* alignedNext = AlignPointer(_next, align);
Byte* end = alignedNext + size;
if (ARCH_UNLIKELY(end > _blockEnd)) {
AllocateBlock(align, size);
alignedNext = AlignPointer(_next, align);
end = _next + size;
}
_next = end;
return alignedNext;
}
private:
using Byte = std::uint8_t;
static Byte* AlignPointer(Byte* ptr, const size_t align) {
const size_t alignMask = align - 1;
return reinterpret_cast<Byte*>(
reinterpret_cast<uintptr_t>(ptr + alignMask) & ~alignMask);
}
TRACE_API void AllocateBlock(const size_t align, const size_t desiredSize);
Byte* _blockEnd = nullptr;
Byte* _next = nullptr;
using BlockPtr = std::unique_ptr<Byte[]>;
std::deque<BlockPtr> _blocks;
size_t _desiredBlockSize;
};
Allocator _alloc;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_DATA_BUFFER_H
+87
View File
@@ -0,0 +1,87 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_DYNAMIC_KEY_H
#define PXR_BASE_TRACE_DYNAMIC_KEY_H
#include "pxr/pxr.h"
#include "pxr/base/trace/staticKeyData.h"
#include "pxr/base/tf/token.h"
PXR_NAMESPACE_OPEN_SCOPE
////////////////////////////////////////////////////////////////////////////////
/// \class TraceDynamicKey
///
/// This class stores data used to create dynamic keys which can be referenced
/// in TraceEvent instances.
///
/// Is a key is known at compile time, it is preferable to use
/// a static constexpr TraceStaticKeyData instance instead.
class TraceDynamicKey {
public:
/// Constructor for TfToken.
TraceDynamicKey(TfToken name) : _key(std::move(name)) {
_data._name = _key.GetText();
}
/// Constructor for string.
TraceDynamicKey(const std::string& name) : _key(name) {
_data._name = _key.GetText();
}
/// Constructor for C string.
TraceDynamicKey(const char* name) : _key(name) {
_data._name = _key.GetText();
}
/// Equality operator.
bool operator == (const TraceDynamicKey& other) const {
return _key == other._key;
}
/// Return a cached hash code for this key.
size_t Hash() const {
return _key.Hash();
}
/// A Hash functor which uses the cached hash which may be used to store
/// keys in a TfHashMap.
struct HashFunctor {
size_t operator()(const TraceDynamicKey& key) const {
return key.Hash();
}
};
/// Returns a reference to TraceStaticKeyData.
const TraceStaticKeyData& GetData() const { return _data; }
private:
TraceStaticKeyData _data;
TfToken _key;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_DYNAMIC_KEY_H
+315
View File
@@ -0,0 +1,315 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_EVENT_H
#define PXR_BASE_TRACE_EVENT_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/category.h"
#include "pxr/base/trace/key.h"
#include "pxr/base/arch/timing.h"
PXR_NAMESPACE_OPEN_SCOPE
class TraceEventData;
////////////////////////////////////////////////////////////////////////////////
/// \class TraceEvent
///
/// This represents an event recorded by a TraceCollector.
/// It contains a key (name), categoryId, timestamp, type, and optional
/// metadata.
///
class TraceEvent {
public:
/// Time in "ticks".
using TimeStamp = uint64_t;
using Key = TraceKey;
/// \name Tag enums to select constructors
/// @{
enum BeginTag { Begin };
enum EndTag { End };
enum TimespanTag { Timespan };
enum MarkerTag { Marker };
enum CounterDeltaTag { CounterDelta };
enum CounterValueTag { CounterValue };
enum DataTag { Data };
/// @}
/// Valid event types
enum class EventType : uint8_t {
Unknown, ///< The event is an unknown type.
Begin, ///< The event represents the beginning timestamp of a scope.
End, ///< The event represents the ending timestamp of a scope.
Timespan, ///< The event represents begin and end timestamp of a scope.
Marker, ///< The event represents an marker without a duration.
CounterDelta, ///< The event represents a change in a counter.
CounterValue, ///< The event represents the value of a counter.
ScopeData,
///< The event stores data that is associated with its enclosing scope.
};
/// The different types of data that can be stored in a TraceEvent instance.
enum class DataType : uint8_t {
String, ///< The event is storing a string.
Boolean, ///< The event is storing a bool.
Int, ///< The event is storing an integer.
UInt, ///< The event is storing an unsigned integer.
Float, ///< The event is storing an double.
Invalid ///< The event is not storing any data.
};
/// Return this event's key.
const Key& GetKey() const { return _key; }
/// Return the time stamp associated with this event.
TRACE_API TimeStamp GetTimeStamp() const;
/// Return the counter value associated with this event.
TRACE_API double GetCounterValue() const;
/// Returns the event's category id.
TraceCategoryId GetCategory() const { return _category; }
/// Returns the start time of a timespan event.
TRACE_API TimeStamp GetStartTimeStamp() const;
/// Returns the end time of a timespan event.
TRACE_API TimeStamp GetEndTimeStamp() const;
/// Returns the data stored in a data event.
TRACE_API TraceEventData GetData() const;
/// Returns the type of the event.
TRACE_API EventType GetType() const;
/// \name Constructors
/// @{
/// Constructor for Begin events that will automatically set the
/// timestamp from the current time.
TraceEvent(BeginTag, const Key& key, TraceCategoryId cat) :
_key(key),
_category(cat),
_type(_InternalEventType::Begin),
_time(ArchGetTickTime()) {
}
/// Constructor for Begin events that takes a specific TimeStamp \a ts.
TraceEvent( BeginTag,
const Key& key,
TimeStamp ts,
TraceCategoryId cat) :
_key(key),
_category(cat),
_type(_InternalEventType::Begin),
_time(ts) {
}
/// Constructor for End events that will automatically set the
/// timestamp from the current time.
TraceEvent(EndTag, const Key& key, TraceCategoryId cat) :
_key(key),
_category(cat),
_type(_InternalEventType::End),
_time(ArchGetTickTime()) {
}
/// Constructor for End events that takes a specific TimeStamp \a ts.
TraceEvent( EndTag,
const Key& key,
TimeStamp ts,
TraceCategoryId cat) :
_key(key),
_category(cat),
_type(_InternalEventType::End),
_time(ts) {
}
/// Constructor for Timespan events that takes a TimeStamp \a starttime
/// and automatically sets the end timestamp from the current time.
TraceEvent(
TimespanTag, const Key& key, TimeStamp startTime, TraceCategoryId cat) :
_key(key),
_category(cat),
_type(_InternalEventType::Timespan),
_time(ArchGetTickTime()) {
new (&_payload) TimeStamp(startTime);
}
/// Constructor for Timespan events that takes the start time and end time.
TraceEvent(
TimespanTag, const Key& key,
TimeStamp startTime, TimeStamp endTime,
TraceCategoryId cat) :
_key(key),
_category(cat),
_type(_InternalEventType::Timespan),
_time(endTime) {
new (&_payload) TimeStamp(startTime);
}
/// Constructor for Marker events that will automatically set the
/// timestamp from the current time.
TraceEvent(MarkerTag, const Key& key, TraceCategoryId cat) :
_key(key),
_category(cat),
_type(_InternalEventType::Marker),
_time(ArchGetTickTime()) {
}
/// Constructor for Mark events that takes a specific TimeStamp \a ts.
TraceEvent( MarkerTag,
const Key& key,
TimeStamp ts,
TraceCategoryId cat) :
_key(key),
_category(cat),
_type(_InternalEventType::Marker),
_time(ts) {
}
/// Constructor for Counter delta events.
TraceEvent( CounterDeltaTag,
const Key& key,
double value,
TraceCategoryId cat) :
_key(key),
_category(cat),
_type(_InternalEventType::CounterDelta),
_time(ArchGetTickTime()) {
new (&_payload) double(value);
}
/// Constructor for Counter value events.
TraceEvent( CounterValueTag,
const Key& key,
double value,
TraceCategoryId cat) :
_key(key),
_category(cat),
_type(_InternalEventType::CounterValue),
_time(ArchGetTickTime()) {
new (&_payload) double(value);
}
/// \name Constructors for data events
/// @{
TraceEvent(DataTag, const Key& key, bool data, TraceCategoryId cat) :
_key(key),
_category(cat),
_dataType(DataType::Boolean),
_type(_InternalEventType::ScopeData),
_time(ArchGetTickTime()) {
new (&_payload) bool(data);
}
TraceEvent(DataTag, const Key& key, int data, TraceCategoryId cat) :
_key(key),
_category(cat),
_dataType(DataType::Int),
_type(_InternalEventType::ScopeData),
_time(ArchGetTickTime()) {
new (&_payload) int64_t(data);
}
TraceEvent(DataTag, const Key& key, int64_t data, TraceCategoryId cat) :
_key(key),
_category(cat),
_dataType(DataType::Int),
_type(_InternalEventType::ScopeData),
_time(ArchGetTickTime()) {
new (&_payload) int64_t(data);
}
TraceEvent(DataTag, const Key& key, uint64_t data, TraceCategoryId cat) :
_key(key),
_category(cat),
_dataType(DataType::UInt),
_type(_InternalEventType::ScopeData),
_time(ArchGetTickTime()) {
new (&_payload) uint64_t(data);
}
TraceEvent(DataTag, const Key& key, double data, TraceCategoryId cat) :
_key(key),
_category(cat),
_dataType(DataType::Float),
_type(_InternalEventType::ScopeData),
_time(ArchGetTickTime()) {
new (&_payload) double(data);
}
TraceEvent(DataTag, const Key& key, const char* data, TraceCategoryId cat) :
_key(key),
_category(cat),
_dataType(DataType::String),
_type(_InternalEventType::ScopeDataLarge),
_time(ArchGetTickTime()) {
new (&_payload) const char*(data);
}
/// @}
// Can move this, but not copy it
TraceEvent(const TraceEvent&) = delete;
TraceEvent& operator= (const TraceEvent&) = delete;
TraceEvent(TraceEvent&&) = default;
TraceEvent& operator= (TraceEvent&&) = default;
/// @}
/// Sets the events timestamp to \p time.
void SetTimeStamp(TimeStamp time) { _time = time; }
private:
// Valid event types. This type has more detail that the public facing
// EventType enum.
enum class _InternalEventType : uint8_t {
Begin,
End,
Timespan,
Marker,
CounterDelta,
CounterValue,
ScopeData,
ScopeDataLarge,
};
using PayloadStorage = std::aligned_storage<8, 8>::type;
Key _key;
TraceCategoryId _category;
DataType _dataType;
_InternalEventType _type;
TimeStamp _time;
PayloadStorage _payload;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_EVENT_H
+264
View File
@@ -0,0 +1,264 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_EVENT_CONTAINER_H
#define PXR_BASE_TRACE_EVENT_CONTAINER_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/event.h"
#include <iterator>
#include <new>
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
///////////////////////////////////////////////////////////////////////////////
/// \class TraceEventContainer
///
/// Holds TraceEvent instances. This container only allows appending events at
/// the end and supports both forward and reverse iteration.
///
class TraceEventContainer {
// Intrusively doubly-linked list node that provides contiguous storage
// for events. Only appending events and iterating held events is
// supported.
class _Node
{
public:
using const_iterator = const TraceEvent *;
// Allocate a new node that is able to hold capacity events.
static _Node* New(size_t capacity);
// Destroys the list starting at head, which must be the first node
// in its list.
static void DestroyList(_Node *head);
// Join the last and first nodes of two lists to form a new list.
static void Join(_Node *lhs, _Node *rhs);
// Returns true if the node cannot hold any more events.
bool IsFull() const { return _end == _sentinel; }
const_iterator begin() const {
const char *p = reinterpret_cast<const char *>(this);
p += sizeof(_Node);
return reinterpret_cast<const TraceEvent *>(p);
}
const_iterator end() const {
return _end;
}
_Node *GetPrevNode() {
return _prev;
}
const _Node *GetPrevNode() const {
return _prev;
}
_Node *GetNextNode() {
return _next;
}
const _Node *GetNextNode() const {
return _next;
}
void ClaimEventEntry() {
++_end;
}
// Remove this node from the linked list to which it belongs.
void Unlink();
private:
_Node(TraceEvent *end, size_t capacity);
~_Node();
private:
union {
struct {
TraceEvent *_end;
TraceEvent *_sentinel;
_Node *_prev;
_Node *_next;
};
// Ensure that _Node is aligned to at least the alignment of
// TraceEvent.
alignas(TraceEvent) char _unused;
};
};
public:
////////////////////////////////////////////////////////////////////////////
/// \class const_iterator
/// Bidirectional iterator of TraceEvents.
///
class const_iterator {
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = const TraceEvent;
using difference_type = int64_t;
using pointer = const TraceEvent*;
using reference = const TraceEvent&;
reference operator*() {
return *_event;
}
pointer operator->() {
return _event;
}
bool operator !=(const const_iterator& other) const {
return !operator==(other);
}
bool operator == (const const_iterator& other) const {
return _event == other._event;
}
const_iterator& operator ++() {
Advance();
return *this;
}
const_iterator operator ++(int) {
const_iterator result(*this);
Advance();
return result;
}
const_iterator& operator --() {
Reverse();
return *this;
}
const_iterator operator --(int) {
const_iterator result(*this);
Reverse();
return result;
}
private:
const_iterator(const _Node *node, const TraceEvent *event)
: _node(node)
, _event(event)
{}
void Advance() {
++_event;
if (_event == _node->end() && _node->GetNextNode()) {
_node = _node->GetNextNode();
_event = _node->begin();
}
}
void Reverse() {
if (_event == _node->begin()) {
_node = _node->GetPrevNode();
_event = _node->end();
}
--_event;
}
const _Node *_node;
const TraceEvent *_event;
friend class TraceEventContainer;
};
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
/// Constructor.
TraceEventContainer();
/// Move Constructor.
TraceEventContainer(TraceEventContainer&&);
/// Move Assignment.
TraceEventContainer& operator=(TraceEventContainer&&);
// No copies
TraceEventContainer(const TraceEventContainer&) = delete;
TraceEventContainer& operator=(const TraceEventContainer&) = delete;
TRACE_API
~TraceEventContainer();
/// \name Subset of stl container interface.
/// @{
template < class... Args>
TraceEvent& emplace_back(Args&&... args) {
TraceEvent *event =
new (_nextEvent++) TraceEvent(std::forward<Args>(args)...);
_back->ClaimEventEntry();
if (_back->IsFull()) {
Allocate();
}
return *event;
}
const_iterator begin() const {
return const_iterator(_front, _front ? _front->begin() : nullptr);
}
const_iterator end() const {
return const_iterator(_back, _back ? _back->end() : nullptr);
}
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
const_reverse_iterator rend() const {
return const_reverse_iterator(begin());
}
bool empty() const { return begin() == end(); }
/// @}
/// Append the events in \p other to the end of this container. This takes
/// ownership of the events that were in \p other.
TRACE_API void Append(TraceEventContainer&& other);
private:
// Allocates a new block of memory for TraceEvent items.
TRACE_API void Allocate();
// Points to where the next event should be constructed.
TraceEvent* _nextEvent;
_Node* _front;
_Node* _back;
size_t _blockSizeBytes;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_EVENT_CONTAINER_H
+97
View File
@@ -0,0 +1,97 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_EVENT_DATA_H
#define PXR_BASE_TRACE_EVENT_DATA_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/event.h"
#include <boost/variant.hpp>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
class JsWriter;
////////////////////////////////////////////////////////////////////////////////
///
/// \class TraceEventData
///
/// This class holds data that can be stored in TraceEvents.
///
class TraceEventData {
public:
/// Ctor for Invalid type.
TraceEventData() : _data(_NoData()) {}
/// Ctor for Bool type.
explicit TraceEventData(bool b) : _data(b) {}
/// Ctor for Int type.
explicit TraceEventData(int64_t i) : _data(i) {}
/// Ctor for UInt type.
explicit TraceEventData(uint64_t i) : _data(i) {}
/// Ctor for Float type.
explicit TraceEventData(double d) : _data(d) {}
/// Ctor for String type.
explicit TraceEventData(const std::string& s) : _data(s) {}
/// Returns the Type of the data stored.
TRACE_API TraceEvent::DataType GetType() const;
/// Returns a pointer to the data or nullptr if the type is not Int.
TRACE_API const int64_t* GetInt() const;
/// Returns a pointer to the data or nullptr if the type is not UInt.
TRACE_API const uint64_t* GetUInt() const;
/// Returns a pointer to the data or nullptr if the type is not Float.
TRACE_API const double* GetFloat() const;
/// Returns a pointer to the data or nullptr if the type is not Bool.
TRACE_API const bool* GetBool() const;
/// Returns a pointer to the data or nullptr if the type is not String.
TRACE_API const std::string* GetString() const;
/// Writes a json representation of the data.
TRACE_API void WriteJson(JsWriter&) const;
private:
// Type that represents no data was stored in an event.
struct _NoData {};
using Variant =
boost::variant<_NoData, std::string, bool, int64_t, uint64_t, double>;
Variant _data;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_EVENT_DATA_H
+121
View File
@@ -0,0 +1,121 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_EVENT_LIST_H
#define PXR_BASE_TRACE_EVENT_LIST_H
#include "pxr/pxr.h"
#include "pxr/base/trace/dataBuffer.h"
#include "pxr/base/trace/dynamicKey.h"
#include "pxr/base/trace/event.h"
#include "pxr/base/trace/eventContainer.h"
#include <list>
#include <unordered_set>
PXR_NAMESPACE_OPEN_SCOPE
////////////////////////////////////////////////////////////////////////////////
/// \class TraceEventList
///
/// This class represents an ordered collection of TraceEvents and the
/// TraceDynamicKeys and data that the events reference.
///
class TraceEventList {
public:
/// Constructor.
TRACE_API TraceEventList();
/// Move Constructor.
TraceEventList(TraceEventList&&) = default;
/// Move Assignment.
TraceEventList& operator=(TraceEventList&&) = default;
// No copies
TraceEventList(const TraceEventList&) = delete;
TraceEventList& operator=(const TraceEventList&) = delete;
/// \name Iterator support.
/// @{
using const_iterator = TraceEventContainer::const_iterator;
const_iterator begin() const { return _events.begin();}
const_iterator end() const { return _events.end();}
using const_reverse_iterator = TraceEventContainer::const_reverse_iterator;
const_reverse_iterator rbegin() const { return _events.rbegin();}
const_reverse_iterator rend() const { return _events.rend();}
/// @}
/// Returns whether there are any events in the list.
bool IsEmpty() const { return _events.empty();}
/// Construct a TraceEvent at the end on the list.
/// Returns a reference to the newly constructed event.
template < class... Args>
const TraceEvent& EmplaceBack(Args&&... args) {
return _events.emplace_back(std::forward<Args>(args)...);
}
/// For speed the TraceEvent class holds a pointer to a TraceStaticKeyData.
/// This method creates a key which can be referenced by events in this
/// container. Returns a TraceKey which will remain valid for the lifetime
/// of the container.
TraceKey CacheKey(const TraceDynamicKey& key) {
KeyCache::const_iterator it = _caches.front().insert(key).first;
return TraceKey(it->GetData());
}
/// Appends the given list to the end of this list. This object will take
/// ownership of the events and keys in the appended list.
TRACE_API void Append(TraceEventList&& other);
/// Copy data to the buffer and return a pointer to the cached data that is
/// valid for the lifetime of the Eventlist.
template < typename T>
decltype(std::declval<TraceDataBuffer>().StoreData(std::declval<T>()))
StoreData(const T& value) {
return _dataCache.StoreData(value);
}
private:
TraceEventContainer _events;
// For speed the TraceEvent class holds a pointer to a TraceStaticKeyData.
// For some events (ones not created by TRACE_FUNCTION and
// TRACE_SCOPE macros), we need to hold onto the TraceDynamicKey to
// keep the reference valid. Using std::list to avoid reallocation,
// keep reference valid by keeping things stable in memory.
using KeyCache =
std::unordered_set<TraceDynamicKey, TraceDynamicKey::HashFunctor>;
std::list<KeyCache> _caches;
TraceDataBuffer _dataCache;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif //PXR_BASE_TRACE_EVENT_LIST_H
+170
View File
@@ -0,0 +1,170 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_EVENT_NODE_H
#define PXR_BASE_TRACE_EVENT_NODE_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/event.h"
#include "pxr/base/trace/eventData.h"
#include "pxr/base/tf/refBase.h"
#include "pxr/base/tf/refPtr.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/tf/declarePtrs.h"
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
TF_DECLARE_REF_PTRS(TraceEventNode);
////////////////////////////////////////////////////////////////////////////////
/// \class TraceEventNode
///
/// TraceEventNode is used to represents call tree of a trace. Each node
/// represents a Begin-End trace event pair, or a single Timespan event. This is
/// useful for timeline views of a trace.
///
class TraceEventNode : public TfRefBase {
public:
using TimeStamp = TraceEvent::TimeStamp;
using AttributeData = TraceEventData;
using AttributeMap = std::multimap<TfToken, AttributeData>;
/// Creates a new root node.
///
static TraceEventNodeRefPtr New() {
return TraceEventNode::New(
TfToken("root"), TraceCategory::Default, 0.0, 0.0, {}, false);
}
/// Creates a new node with \p key, \p category, \p beginTime and
/// \p endTime.
static TraceEventNodeRefPtr New(const TfToken &key,
const TraceCategoryId category,
const TimeStamp beginTime,
const TimeStamp endTime,
TraceEventNodeRefPtrVector&& children,
const bool separateEvents) {
return TfCreateRefPtr(
new TraceEventNode(
key,
category,
beginTime,
endTime,
std::move(children),
separateEvents));
}
/// Appends a new child node with \p key, \p category, \p beginTime and
/// \p endTime.
TraceEventNodeRefPtr Append(const TfToken &key,
TraceCategoryId category,
TimeStamp beginTime,
TimeStamp endTime,
bool separateEvents);
/// Appends \p node as a child node.
void Append(TraceEventNodeRefPtr node);
/// Returns the name of this node.
TfToken GetKey() { return _key;}
/// Returns the category of this node.
TraceCategoryId GetCategory() const { return _category; }
/// Sets this node's begin and end time to the time extents of its direct
/// children.
void SetBeginAndEndTimesFromChildren();
/// \name Profile Data Accessors
/// @{
/// Returns the time that this scope started.
TimeStamp GetBeginTime() { return _beginTime; }
/// Returns the time that this scope ended.
TimeStamp GetEndTime() { return _endTime; }
/// @}
/// \name Children Accessors
/// @{
/// Returns references to the children of this node.
const TraceEventNodeRefPtrVector &GetChildrenRef() {
return _children;
}
/// @}
/// Return the data associated with this node.
const AttributeMap& GetAttributes() const { return _attributes; }
/// Add data to this node.
void AddAttribute(const TfToken& key, const AttributeData& attr);
/// Returns whether this node was created from a Begin-End pair or a single
/// Timespan event.
bool IsFromSeparateEvents() const {
return _fromSeparateEvents;
}
private:
TraceEventNode(
const TfToken &key,
TraceCategoryId category,
TimeStamp beginTime,
TimeStamp endTime,
TraceEventNodeRefPtrVector&& children,
bool separateEvents)
: _key(key)
, _category(category)
, _beginTime(beginTime)
, _endTime(endTime)
, _children(std::move(children))
, _fromSeparateEvents(separateEvents)
{}
TfToken _key;
TraceCategoryId _category;
TimeStamp _beginTime;
TimeStamp _endTime;
TraceEventNodeRefPtrVector _children;
bool _fromSeparateEvents;
AttributeMap _attributes;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_EVENT_NODE_H
+134
View File
@@ -0,0 +1,134 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_EVENT_TREE_H
#define PXR_BASE_TRACE_EVENT_TREE_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/event.h"
#include "pxr/base/trace/eventNode.h"
#include "pxr/base/trace/threads.h"
#include "pxr/base/tf/refBase.h"
#include "pxr/base/tf/refPtr.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/tf/weakBase.h"
#include "pxr/base/tf/weakPtr.h"
#include "pxr/base/tf/declarePtrs.h"
#include <functional>
#include <vector>
#include <unordered_map>
PXR_NAMESPACE_OPEN_SCOPE
class TraceCollection;
class JsWriter;
TF_DECLARE_WEAK_AND_REF_PTRS(TraceEventTree);
////////////////////////////////////////////////////////////////////////////////
/// \class TraceEventTree
///
/// This class contains a timeline call tree and a map of counters to their
/// values over time.
///
///
class TraceEventTree : public TfRefBase, public TfWeakBase {
public:
using CounterValues = std::vector<std::pair<TraceEvent::TimeStamp, double>>;
using CounterValuesMap =
std::unordered_map<TfToken, CounterValues, TfToken::HashFunctor>;
using CounterMap =
std::unordered_map<TfToken, double, TfToken::HashFunctor>;
using MarkerValues = std::vector<std::pair<TraceEvent::TimeStamp, TraceThreadId>>;
using MarkerValuesMap =
std::unordered_map<TfToken, MarkerValues, TfToken::HashFunctor>;
/// Creates a new TraceEventTree instance from the data in \p collection
/// and \p initialCounterValues.
TRACE_API static TraceEventTreeRefPtr New(
const TraceCollection& collection,
const CounterMap* initialCounterValues = nullptr);
static TraceEventTreeRefPtr New() {
return TfCreateRefPtr(
new TraceEventTree(TraceEventNode::New()));
}
static TraceEventTreeRefPtr New(
TraceEventNodeRefPtr root,
CounterValuesMap counters,
MarkerValuesMap markers) {
return TfCreateRefPtr(
new TraceEventTree(root, std::move(counters), std::move(markers)));
}
/// Returns the root node of the tree.
const TraceEventNodeRefPtr& GetRoot() const { return _root; }
/// Returns the map of counter values.
const CounterValuesMap& GetCounters() const { return _counters; }
/// Returns the map of markers values.
const MarkerValuesMap& GetMarkers() const { return _markers; }
/// Return the final value of the counters in the report.
CounterMap GetFinalCounterValues() const;
/// Writes a JSON object representing the data in the call tree that
/// conforms to the Chrome Trace format.
using ExtraFieldFn = std::function<void(JsWriter&)>;
TRACE_API void WriteChromeTraceObject(
JsWriter& writer, ExtraFieldFn extraFields = ExtraFieldFn()) const;
/// Adds the contexts of \p tree to this tree.
TRACE_API void Merge(const TraceEventTreeRefPtr& tree);
/// Adds the data from \p collection to this tree.
TRACE_API TraceEventTreeRefPtr Add(const TraceCollection& collection);
private:
TraceEventTree(TraceEventNodeRefPtr root)
: _root(root) {}
TraceEventTree( TraceEventNodeRefPtr root,
CounterValuesMap counters,
MarkerValuesMap markers)
: _root(root)
, _counters(std::move(counters))
, _markers(std::move(markers)) {}
// Root of the call tree.
TraceEventNodeRefPtr _root;
// Counter data of the trace.
CounterValuesMap _counters;
// Marker data of the trace.
MarkerValuesMap _markers;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_EVENT_TREE_H
+75
View File
@@ -0,0 +1,75 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_KEY_H
#define PXR_BASE_TRACE_KEY_H
#include "pxr/pxr.h"
#include "pxr/base/trace/staticKeyData.h"
PXR_NAMESPACE_OPEN_SCOPE
////////////////////////////////////////////////////////////////////////////////
/// \class TraceKey
///
/// A wrapper around a TraceStaticKeyData pointer that is stored in TraceEvent
/// instances.
///
class TraceKey {
public:
/// Constructor.
constexpr TraceKey(const TraceStaticKeyData& data) : _ptr(&data) {}
/// Equality comparison.
bool operator == (const TraceKey& other) const {
if (_ptr == other._ptr) {
return true;
} else {
return *_ptr == *other._ptr;
}
}
/// Hash function.
size_t Hash() const {
return reinterpret_cast<size_t>(_ptr)/sizeof(TraceStaticKeyData);
}
/// A Hash functor which may be used to store keys in a TfHashMap.
struct HashFunctor {
size_t operator()(const TraceKey& key) const {
return key.Hash();
}
};
private:
const TraceStaticKeyData* _ptr;
// TraceCollection converts TraceKeys to TfTokens for visitors.
friend class TraceCollection;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_KEY_H
+209
View File
@@ -0,0 +1,209 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_REPORTER_H
#define PXR_BASE_TRACE_REPORTER_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/event.h"
#include "pxr/base/trace/aggregateNode.h"
#include "pxr/base/trace/reporterBase.h"
#include "pxr/base/tf/declarePtrs.h"
#include "pxr/base/tf/mallocTag.h"
#include "pxr/base/tf/staticTokens.h"
#include <iosfwd>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
#define TRACE_REPORTER_TOKENS \
((warningString, "WARNING:"))
TF_DECLARE_PUBLIC_TOKENS(TraceReporterTokens, TRACE_API, TRACE_REPORTER_TOKENS);
TF_DECLARE_WEAK_AND_REF_PTRS(TraceAggregateTree);
TF_DECLARE_WEAK_AND_REF_PTRS(TraceEventNode);
TF_DECLARE_WEAK_AND_REF_PTRS(TraceEventTree);
TF_DECLARE_WEAK_AND_REF_PTRS(TraceReporter);
class TraceCollectionAvailable;
////////////////////////////////////////////////////////////////////////////////
/// \class TraceReporter
///
/// This class converts streams of TraceEvent objects into call trees which
/// can then be used as a data source to a GUI or written out to a file.
///
class TraceReporter :
public TraceReporterBase {
public:
TF_MALLOC_TAG_NEW("Trace", "TraceReporter");
using This = TraceReporter;
using ThisPtr = TraceReporterPtr;
using ThisRefPtr = TraceReporterRefPtr;
using Event = TraceEvent;
using TimeStamp = TraceEvent::TimeStamp;
using CounterMap = TfHashMap<TfToken, double, TfToken::HashFunctor>;
/// Create a new reporter with \a label and \a dataSource.
static ThisRefPtr New(const std::string& label,
DataSourcePtr dataSource) {
return TfCreateRefPtr(new This(label, std::move(dataSource)));
}
/// Create a new reporter with \a label and no data source.
static ThisRefPtr New(const std::string& label) {
return TfCreateRefPtr(new This(label, nullptr));
}
/// Returns the global reporter.
TRACE_API static TraceReporterPtr GetGlobalReporter();
/// Destructor.
TRACE_API virtual ~TraceReporter();
/// Return the label associated with this reporter.
const std::string& GetLabel() {
return _label;
}
/// \name Report Generation.
/// @{
/// Generates a report to the ostream \a s, dividing all times by
/// \a iterationCount.
TRACE_API void Report(
std::ostream &s,
int iterationCount=1);
/// Generates a report of the times to the ostream \a s.
TRACE_API void ReportTimes(std::ostream &s);
/// Generates a timeline trace report suitable for viewing in
/// Chrome's trace viewer.
TRACE_API void ReportChromeTracing(std::ostream &s);
/// @}
/// Returns the root node of the aggregated call tree.
TRACE_API TraceAggregateNodePtr GetAggregateTreeRoot();
/// Returns the root node of the call tree.
TRACE_API TraceEventNodeRefPtr GetEventRoot();
/// Returns the event call tree
TRACE_API TraceEventTreeRefPtr GetEventTree();
/// \name Counters
/// @{
/// Returns a map of counters (counter keys), associated with their total
/// accumulated value. Each individual event node in the tree may also hold
/// on to an inclusive and exclusive value for the given counter.
TRACE_API const CounterMap & GetCounters() const;
/// Returns the numeric index associated with a counter key. Counter values
/// on the event nodes will have to be looked up by the numeric index.
TRACE_API int GetCounterIndex(const TfToken &key) const;
/// Add a counter to the reporter. This method can be used to restore a
/// previous trace state and tree. Note, that the counter being added must
/// have a unique key and index. The method will return false if a key or
/// index already exists.
TRACE_API bool AddCounter(const TfToken &key, int index, double totalValue);
/// @}
/// This fully re-builds the event and aggregate trees from whatever the
/// current collection holds. It is ok to call this multiple times in case
/// the collection gets appended on inbetween.
///
/// If we want to have multiple reporters per collector, this will need to
/// be changed so that all reporters reporting on a collector update their
/// respective trees.
TRACE_API void UpdateTraceTrees();
/// Clears event tree and counters.
TRACE_API void ClearTree();
/// \name Report options.
/// @{
/// This affects only stack trace event reporting. If \c true then all
/// events in a function are grouped together otherwise events are split
/// out by address.
TRACE_API void SetGroupByFunction(bool);
/// Returns the current group-by-function state.
TRACE_API bool GetGroupByFunction() const;
/// When stack trace event reporting, this sets whether or not recursive
/// calls are folded in the output. Recursion folding is useful when
/// the stacks contain deep recursive structures.
TRACE_API void SetFoldRecursiveCalls(bool);
/// Returns the current setting for recursion folding for stack trace
/// event reporting.
TRACE_API bool GetFoldRecursiveCalls() const;
/// @}
/// Creates a valid TraceAggregateNode::Id object.
/// This should be used by very few clients for certain special cases.
/// For most cases, the TraceAggregateNode::Id object should be created and
/// populated internally within the Reporter object itself.
TRACE_API static TraceAggregateNode::Id CreateValidEventId();
protected:
TRACE_API TraceReporter(const std::string& label,
DataSourcePtr dataSource);
private:
void _ProcessCollection(const TraceReporterBase::CollectionPtr&) override;
void _RebuildEventAndAggregateTrees();
void _PrintTimes(std::ostream &s);
private:
std::string _label;
bool _groupByFunction;
bool _foldRecursiveCalls;
TraceAggregateTreeRefPtr _aggregateTree;
TraceEventTreeRefPtr _eventTree;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_REPORTER_H
+87
View File
@@ -0,0 +1,87 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_REPORTER_BASE_H
#define PXR_BASE_TRACE_REPORTER_BASE_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/collectionNotice.h"
#include "pxr/base/trace/collection.h"
#include "pxr/base/trace/reporterDataSourceBase.h"
#include "pxr/base/tf/declarePtrs.h"
#include <tbb/concurrent_vector.h>
#include <ostream>
PXR_NAMESPACE_OPEN_SCOPE
TF_DECLARE_WEAK_AND_REF_PTRS(TraceReporterBase);
////////////////////////////////////////////////////////////////////////////////
/// \class TraceReporterBase
///
/// This class is a base class for report implementations. It handles receiving
/// and processing of TraceCollections.
///
///
class TraceReporterBase :
public TfRefBase, public TfWeakBase {
public:
using This = TraceReporterBase;
using ThisPtr = TraceReporterBasePtr;
using ThisRefPtr = TraceReporterBaseRefPtr;
using CollectionPtr = std::shared_ptr<TraceCollection>;
using DataSourcePtr = std::unique_ptr<TraceReporterDataSourceBase>;
/// Constructor taking ownership of \p dataSource.
TRACE_API TraceReporterBase(DataSourcePtr dataSource);
/// Destructor.
TRACE_API virtual ~TraceReporterBase();
/// Write all collections that were processed by this reporter to \p ostr.
TRACE_API bool SerializeProcessedCollections(std::ostream& ostr) const;
protected:
/// Removes all references to TraceCollections.
TRACE_API void _Clear();
/// Gets the latest data from the TraceCollector singleton and processes all
/// collections that have been received since the last call to _Update().
TRACE_API void _Update();
/// Called once per collection from _Update()
virtual void _ProcessCollection(const CollectionPtr&) = 0;
private:
DataSourcePtr _dataSource;
tbb::concurrent_vector<CollectionPtr> _processedCollections;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_REPORTER_BASE_H
@@ -0,0 +1,60 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_REPORTER_DATA_SOURCE_BASE_H
#define PXR_BASE_TRACE_REPORTER_DATA_SOURCE_BASE_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/collection.h"
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
////////////////////////////////////////////////////////////////////////////////
/// \class TraceReporterDataSourceBase
///
/// This class is a base class for TraceReporterBase data sources.
/// TraceReporterBase uses an instance of a TraceReporterDataSourceBase derived
/// class to access TraceCollections.
///
class TraceReporterDataSourceBase {
public:
using CollectionPtr = std::shared_ptr<TraceCollection>;
/// Destructor
TRACE_API virtual ~TraceReporterDataSourceBase();
/// Removes all references to TraceCollections.
virtual void Clear() = 0;
/// Returns the next TraceCollections which need to be processed.
virtual std::vector<CollectionPtr> ConsumeData() = 0;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_REPORTER_DATA_SOURCE_BASE_H
@@ -0,0 +1,73 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_REPORTER_DATA_SOURCE_COLLECTION_H
#define PXR_BASE_TRACE_REPORTER_DATA_SOURCE_COLLECTION_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/collection.h"
#include "pxr/base/trace/reporterDataSourceBase.h"
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
////////////////////////////////////////////////////////////////////////////////
/// \class TraceReporterDataSourceCollection
///
/// This class is an implementation of TraceReporterDataSourceBase which provides
/// access to a set number of TraceCollection instances. This class is useful if
/// you want to generate reports from serialized TraceCollections.
///
class TraceReporterDataSourceCollection : public TraceReporterDataSourceBase {
public:
using This = TraceReporterDataSourceCollection;
using ThisRefPtr = std::unique_ptr<This>;
static ThisRefPtr New(CollectionPtr collection) {
return ThisRefPtr(new This(collection));
}
static ThisRefPtr New(std::vector<CollectionPtr> collections) {
return ThisRefPtr(new This(std::move(collections)));
}
/// Removes all references to TraceCollections.
TRACE_API void Clear() override;
/// Returns the next TraceCollections which need to be processed.
TRACE_API std::vector<CollectionPtr> ConsumeData() override;
private:
TRACE_API TraceReporterDataSourceCollection(CollectionPtr collection);
TRACE_API TraceReporterDataSourceCollection(
std::vector<CollectionPtr> collections);
std::vector<CollectionPtr> _data;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_REPORTER_DATA_SOURCE_COLLECTION_H
@@ -0,0 +1,89 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_REPORTER_DATA_SOURCE_COLLECTOR_H
#define PXR_BASE_TRACE_REPORTER_DATA_SOURCE_COLLECTOR_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/collection.h"
#include "pxr/base/trace/collectionNotice.h"
#include "pxr/base/trace/reporterDataSourceBase.h"
#include "pxr/base/tf/declarePtrs.h"
#include <tbb/concurrent_queue.h>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
TF_DECLARE_WEAK_PTRS(TraceReporterDataSourceCollector);
////////////////////////////////////////////////////////////////////////////////
/// \class TraceReporterDataSourceCollector
///
/// This class is an implementation of TraceReporterDataSourceBase which
/// retrieves TraceCollections from the TraceCollector singleton.
///
class TraceReporterDataSourceCollector :
public TraceReporterDataSourceBase, public TfWeakBase {
public:
using This = TraceReporterDataSourceCollector;
using ThisPtr = TraceReporterDataSourceCollectorPtr;
using ThisRefPtr = std::unique_ptr<This>;
/// Creates a new TraceReporterDataSourceCollector.
static ThisRefPtr New() {
return ThisRefPtr(new This());
}
/// Creates a new TraceReporterDataSourceCollector which will only listen to
/// the TraceCollectionAvailable notice when \p accept returns true.
/// \p accept must be thread-safe.
static ThisRefPtr New(std::function<bool()> accept) {
return ThisRefPtr(new This(std::move(accept)));
}
/// Removes all references to TraceCollections.
TRACE_API void Clear() override;
/// Returns the next TraceCollections which need to be processed.
TRACE_API std::vector<CollectionPtr> ConsumeData() override;
private:
TRACE_API TraceReporterDataSourceCollector();
TRACE_API TraceReporterDataSourceCollector(std::function<bool()> accept);
// Add the new collection to the pending queue.
void _OnTraceCollection(const TraceCollectionAvailable&);
std::function<bool()> _accept;
tbb::concurrent_queue<CollectionPtr> _pendingCollections;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_REPORTER_DATA_SOURCE_COLLECTOR_H
+67
View File
@@ -0,0 +1,67 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_SERIALIZATION_H
#define PXR_BASE_TRACE_SERIALIZATION_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/collection.h"
#include <istream>
#include <ostream>
#include <memory>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
////////////////////////////////////////////////////////////////////////////////
/// \class TraceSerialization
///
/// This class contains methods to read and write TraceCollection.
///
class TraceSerialization {
public:
/// Writes \p col to \p ostr.
/// Returns true if the write was successful, false otherwise.
TRACE_API static bool Write(std::ostream& ostr,
const std::shared_ptr<TraceCollection>& col);
/// Writes \p collections to \p ostr.
/// Returns true if the write was successful, false otherwise.
TRACE_API static bool Write(
std::ostream& ostr,
const std::vector<std::shared_ptr<TraceCollection>>& collections);
/// Tries to create a TraceCollection from the contexts of \p istr.
/// Returns a pointer to the created collection if it was successful.
/// If there is an error reading \p istr, \p error will be populated with a
/// description.
TRACE_API static std::unique_ptr<TraceCollection> Read(std::istream& istr,
std::string* error = nullptr);
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_SERIALIZATION_H
+102
View File
@@ -0,0 +1,102 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_STATIC_KEY_DATA_H
#define PXR_BASE_TRACE_STATIC_KEY_DATA_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include <cstddef>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
////////////////////////////////////////////////////////////////////////////////
///
/// \class TraceStaticKeyData
///
/// This class holds data necessary to create keys for TraceEvent instances.
/// This class is meant to be used as constexpr static data.
///
class TraceStaticKeyData {
public:
/// \class StringLiteral
///
/// This is a helper class for the constructors of TraceStaticKeyData.
///
class StringLiteral {
public:
/// Constructor from string literals.
template <size_t N>
constexpr StringLiteral(const char(&s)[N]) : str(s) {}
/// Default Constructor.
constexpr StringLiteral() : str(nullptr) {}
private:
const char* str;
friend class TraceStaticKeyData;
};
/// Constructor for a \p name.
constexpr TraceStaticKeyData(const StringLiteral name)
: _name(name.str) {}
/// Constructor for a function (\p func, \p prettyFunc) and optional
/// scope \p name.
constexpr TraceStaticKeyData(
const StringLiteral func,
const StringLiteral prettyFunc,
const StringLiteral name = StringLiteral())
: _funcName(func.str)
, _prettyFuncName(prettyFunc.str)
, _name(name.str) {}
/// Equality comparison. Inequality is also defined.
TRACE_API
bool operator == (const TraceStaticKeyData& other) const;
bool operator != (const TraceStaticKeyData& other) const {
return !(*this == other);
}
/// Returns the string representation of the key data.
TRACE_API
std::string GetString() const;
private:
TraceStaticKeyData() {}
const char* _funcName = nullptr;
const char* _prettyFuncName = nullptr;
const char* _name = nullptr;
friend class TraceDynamicKey;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_STATIC_KEY_DATA_H
+67
View File
@@ -0,0 +1,67 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_STRING_HASH_H
#define PXR_BASE_TRACE_STRING_HASH_H
#include "pxr/pxr.h"
#include <cstdint>
PXR_NAMESPACE_OPEN_SCOPE
///////////////////////////////////////////////////////////////////////////////
///
/// \class TraceStringHash
///
/// This class provides a function to compute compile time hashes for string
/// literals.
///
class TraceStringHash {
public:
/// Computes a compile time hash of \p str.
template <int N>
static constexpr std::uint32_t Hash(const char (&str)[N]) {
return djb2HashStr<N-1>(str);
}
private:
// Recursive function computing the xor variant of the djb2 hash
// function.
template <int N>
static constexpr std::uint32_t djb2HashStr(const char* str) {
return (djb2HashStr<N-1>(str) * 33) ^ str[N-1];
}
};
// Template recursion base case.
template <>
constexpr std::uint32_t TraceStringHash::djb2HashStr<0>(const char* str) {
return 5381;
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif //PXR_BASE_TRACE_STRING_HASH_H
+68
View File
@@ -0,0 +1,68 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_THREADS_H
#define PXR_BASE_TRACE_THREADS_H
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
////////////////////////////////////////////////////////////////////////////////
/// \class ThraceThreadId
///
/// This class represents an identifier for a thread.
///
class TraceThreadId {
public:
/// Constructor which creates an identifier based on std::thread_id. .
/// It is either"Main Thread" if this id is marked as the main thread or
/// "Thread XXX" where XXX is the string representation of the thread id.
TRACE_API TraceThreadId();
/// Constructor which creates an identifier from \p id.
TRACE_API explicit TraceThreadId(const std::string& id);
/// Returns the string representation of the id.
const std::string& ToString() const { return _id; }
/// Equality operator.
TRACE_API bool operator==(const TraceThreadId&) const;
/// Less than operator.
TRACE_API bool operator<(const TraceThreadId&) const;
private:
std::string _id;
};
inline TraceThreadId TraceGetThreadId() {
return TraceThreadId();
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_THREADS_H
+352
View File
@@ -0,0 +1,352 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_TRACE_TRACE_H
#define PXR_BASE_TRACE_TRACE_H
/// \file trace/trace.h
#include "pxr/pxr.h"
#include "pxr/base/trace/api.h"
#include "pxr/base/trace/collector.h"
#include "pxr/base/tf/preprocessorUtilsLite.h"
#include <atomic>
#if !defined(TRACE_DISABLE)
/// Records a timestamp when constructed and a timespan event when destructed,
/// using the name of the function or method as the key.
#define TRACE_FUNCTION() \
_TRACE_FUNCTION_INSTANCE(__LINE__, __ARCH_FUNCTION__, __ARCH_PRETTY_FUNCTION__)
/// Records a timestamp when constructed and a timespan event when destructed,
/// using \a name as the key.
#define TRACE_SCOPE(name) \
_TRACE_SCOPE_INSTANCE(__LINE__, name)
/// Records a timestamp when constructed and a timespan event when destructed,
/// using the name of the function concatenated with \a name as the key.
#define TRACE_FUNCTION_SCOPE(name) \
_TRACE_FUNCTION_SCOPE_INSTANCE( \
__LINE__, __ARCH_FUNCTION__, __ARCH_PRETTY_FUNCTION__, name)
/// Records a timestamp when constructed, using \a name as the key.
#define TRACE_MARKER(name) \
_TRACE_MARKER_INSTANCE(__LINE__, name)
/// Records a timestamp when constructed, using \a name as the key.
#define TRACE_MARKER_DYNAMIC(name) \
_TRACE_MARKER_DYNAMIC_INSTANCE(__LINE__, name)
/// Records a counter \a delta using the \a name as the counter key. The delta can
/// be positive or negative. A positive delta will increment the total counter
/// value, whereas a negative delta will decrement it. The recorded value will
/// be stored at the currently traced scope, and will propagate up to the
/// parent scopes.
#define TRACE_COUNTER_DELTA(name, delta) \
_TRACE_COUNTER_INSTANCE(__LINE__, name, delta, /* isDelta */ true)
/// Records a counter delta using the name as the counter key. Similar to
/// TRACE_COUNTER_DELTA except that \p name does not need to be a compile time
/// string.
/// \sa TRACE_COUNTER_DELTA
#define TRACE_COUNTER_DELTA_DYNAMIC(name, delta) \
TraceCollector::GetInstance().RecordCounterDelta(name, delta);
/// Records a counter value using the name as the counter key. The recorded
/// value will be stored at the currently traced scope, and will propagate up to
/// the parent scopes.
#define TRACE_COUNTER_VALUE(name, value) \
_TRACE_COUNTER_INSTANCE(__LINE__, name, value, /* isDelta */ false)
/// Records a counter value using the name as the counter key. Similar to
/// TRACE_COUNTER_VALUE except that \p name does not need to be a compile time
/// string.
/// \sa TRACE_COUNTER_VALUE
#define TRACE_COUNTER_VALUE_DYNAMIC(name, value) \
TraceCollector::GetInstance().RecordCounterValue(name, value);
/// Records a counter value using the name as the counter key. The value can
/// be positive or negative. A positive value will increment the total counter
/// value, whereas a negative value will decrement it. The recorded value will
/// be stored at the currently traced scope, and will propagate up to the
/// parent scopes.
///
/// This macro provides the same functionality as TRACE_COUNTER_DELTA, but takes
/// a section of code in brackets, which assumes that a value will be
/// assigned to 'value'. The section of code will not be executed, when
/// tracing is turned off, which makes it possible to gather counter values
/// from potentially expensive logic, without incurring an overhead with
/// tracing turned off.
///
/// Usage:
///
/// TRACE_COUNTER_DELTA_CODE("My counter", {
/// value = _ComputeExpensiveCounterValue();
/// })
#define TRACE_COUNTER_DELTA_CODE(name, code) \
_TRACE_COUNTER_CODE_INSTANCE(__LINE__, name, code, true)
/// Records a begin event when constructed and an end event when destructed,
/// using name of the function or method and the supplied name as the key.
/// Unlike TRACE_FUNCTION, the name argument will be evaluated each time this
/// macro is invoked. This allows for a single TRACE_FUNCTION to track time
/// under different keys, but incurs greater overhead.
#define TRACE_FUNCTION_DYNAMIC(name) \
_TRACE_FUNCTION_DYNAMIC_INSTANCE(__LINE__, __ARCH_FUNCTION__, __ARCH_PRETTY_FUNCTION__, name)
/// Records a begin event when constructed and an end event when destructed,
/// using \a name as the key. Unlike TRACE_SCOPE, the name argument will
/// be evaluated each time this macro is invoked. This allows for a single
/// TRACE_SCOPE to track time under different keys, but incurs greater
/// overhead.
#define TRACE_SCOPE_DYNAMIC(name) \
_TRACE_SCOPE_DYNAMIC_INSTANCE(__LINE__, name)
/// These pair a uniquely named TraceScopeHolder with a TraceScopeAuto.
/// Together these will register a TraceScope only the first time the
/// code is executed or if the TraceScope expires. Otherwise, the held
/// TraceScope will be used to record begin and end events.
#define _TRACE_FUNCTION_INSTANCE(instance, name, prettyName) \
constexpr static PXR_NS::TraceStaticKeyData \
TF_PP_CAT(TraceKeyData_, instance)(name, prettyName); \
PXR_NS::TraceScopeAuto TF_PP_CAT(TraceScopeAuto_, instance)(\
TF_PP_CAT(TraceKeyData_, instance));
#define _TRACE_SCOPE_INSTANCE(instance, name) \
constexpr static PXR_NS::TraceStaticKeyData \
TF_PP_CAT(TraceKeyData_, instance)(name); \
PXR_NS::TraceScopeAuto TF_PP_CAT(TraceScopeAuto_, instance)(\
TF_PP_CAT(TraceKeyData_, instance));
#define _TRACE_FUNCTION_SCOPE_INSTANCE(instance, name, prettyName, scopeName) \
constexpr static PXR_NS::TraceStaticKeyData \
TF_PP_CAT(TraceKeyData_, instance)(name, prettyName, scopeName); \
PXR_NS::TraceScopeAuto TF_PP_CAT(TraceScopeAuto_, instance)(\
TF_PP_CAT(TraceKeyData_, instance));
#define _TRACE_MARKER_INSTANCE(instance, name) \
constexpr static PXR_NS::TraceStaticKeyData \
TF_PP_CAT(TraceKeyData_, instance)(name); \
TraceCollector::GetInstance().MarkerEventStatic(TF_PP_CAT(TraceKeyData_, instance));
#define _TRACE_COUNTER_INSTANCE(instance, name, value, isDelta) \
constexpr static PXR_NS::TraceStaticKeyData \
TF_PP_CAT(TraceKeyData_, instance)(name); \
static PXR_NS::TraceCounterHolder \
TF_PP_CAT(TraceCounterHolder_, instance) \
(TF_PP_CAT(TraceKeyData_, instance)); \
TF_PP_CAT(TraceCounterHolder_, instance).Record(value, isDelta);
#define _TRACE_COUNTER_CODE_INSTANCE(instance, name, code, isDelta) \
static PXR_NS::TraceCounterHolder \
TF_PP_CAT(TraceCounterHolder_, instance)(name); \
if (TF_PP_CAT(TraceCounterHolder_, instance).IsEnabled()) { \
double value = 0.0; \
code \
TF_PP_CAT(TraceCounterHolder_, instance).RecordDelta(value, isDelta); \
}
#define _TRACE_FUNCTION_DYNAMIC_INSTANCE(instance, fnName, fnPrettyName, name) \
PXR_NS::TraceAuto TF_PP_CAT(TraceAuto_, instance)(fnName, fnPrettyName, name)
#define _TRACE_SCOPE_DYNAMIC_INSTANCE(instance, str) \
PXR_NS::TraceAuto TF_PP_CAT(TraceAuto_, instance)(str)
#define _TRACE_MARKER_DYNAMIC_INSTANCE(instance, name) \
TraceCollector::GetInstance().MarkerEvent(name);
#else // TRACE_DISABLE
#define TRACE_FUNCTION()
#define TRACE_FUNCTION_DYNAMIC(name)
#define TRACE_SCOPE(name)
#define TRACE_SCOPE_DYNAMIC(name)
#define TRACE_FUNCTION_SCOPE(name)
#define TRACE_MARKER(name)
#define TRACE_MARKER_DYNAMIC(name)
#endif // TRACE_DISABLE
PXR_NAMESPACE_OPEN_SCOPE
////////////////////////////////////////////////////////////////////////////////
/// \class TraceScopeAuto
///
/// A class which records a timestamp when it is created and a
/// scope event when it is destructed.
///
class TraceScopeAuto {
public:
/// Constructor for TRACE_FUNCTION macro.
///
explicit TraceScopeAuto(const TraceStaticKeyData& key)
: _key(nullptr)
, _start(0) {
if (ARCH_UNLIKELY(TraceCollector::IsEnabled())) {
// Init the key if needed.
_key = &key;
_start = ArchGetTickTime();
}
}
/// Constructor that also records scope arguments.
///
template < typename... Args>
TraceScopeAuto(const TraceStaticKeyData& key, Args&&... args)
: TraceScopeAuto(key) {
if (ARCH_UNLIKELY(_key)) {
TraceCollector::GetInstance().ScopeArgs(std::forward<Args>(args)...);
}
}
/// Destructor.
///
~TraceScopeAuto() {
if (ARCH_UNLIKELY(_key)) {
TraceCollector::GetInstance().Scope(*_key, _start);
}
}
private:
const TraceStaticKeyData* _key;
TraceEvent::TimeStamp _start;
};
////////////////////////////////////////////////////////////////////////////////
/// \class TraceAuto
///
/// A class which records a begin event when it is constructed, and a matching
/// end event when it is destructed. It is intended to help ensure begin-end
/// pairing correctness when the begin-end pairing can be expressed by automatic
/// variable lifetime.
///
/// The TRACE_FUNCTION() macro may be even more convenient in some
/// circumstances.
///
struct TraceAuto {
/// Constructor taking function name, pretty function name and a scope name.
///
TraceAuto(const char *funcName, const char *prettyFuncName,
const std::string &name)
: _key(_CreateKeyString(funcName, prettyFuncName, name)) {
std::atomic_thread_fence(std::memory_order_seq_cst);
_collector = &TraceCollector::GetInstance();
_collector->BeginEvent(_key);
std::atomic_thread_fence(std::memory_order_seq_cst);
}
/// Constructor taking a TfToken key.
///
explicit TraceAuto(const TfToken& key)
: _key(key) {
std::atomic_thread_fence(std::memory_order_seq_cst);
_collector = &TraceCollector::GetInstance();
_collector->BeginEvent(_key);
std::atomic_thread_fence(std::memory_order_seq_cst);
}
/// Constructor taking a string key.
///
explicit TraceAuto(const std::string& key)
: TraceAuto(TfToken(key)) {}
// Non-copyable
//
TraceAuto(const TraceAuto &) = delete;
TraceAuto& operator=(const TraceAuto &) = delete;
// Non-movable
//
TraceAuto(TraceAuto &&) = delete;
TraceAuto& operator=(TraceAuto &&) = delete;
/// Destructor.
///
~TraceAuto() {
std::atomic_thread_fence(std::memory_order_seq_cst);
_collector->EndEvent(_key);
std::atomic_thread_fence(std::memory_order_seq_cst);
}
private:
static std::string _CreateKeyString(
const char *funcName,
const char *prettyFuncName,
const std::string &name) {
std::string key = ArchGetPrettierFunctionName(funcName, prettyFuncName);
key += " [";
key += name;
key += "]";
return key;
}
TraceCollector* _collector;
TraceDynamicKey _key;
};
////////////////////////////////////////////////////////////////////////////////
/// \class TraceCounterHolder
///
/// Holds on to a counter key, as well as the global
/// collector for fast lookup.
///
class TraceCounterHolder {
public:
/// Constructor used by TRACE_COUNTER_* macro.
///
explicit TraceCounterHolder(const TraceKey& key)
: _key(key) {}
/// Returns whether the TraceCollector is enabled or not.
///
bool IsEnabled() const {
return TraceCollector::IsEnabled();
}
/// Records a counter delta \p value if the TraceCollector is enabled.
///
void Record(double value, bool delta) {
if (delta) {
TraceCollector::GetInstance().RecordCounterDelta(_key, value);
} else {
TraceCollector::GetInstance().RecordCounterValue(_key, value);
}
}
private:
TraceKey _key;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_TRACE_TRACE_H