1 /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #include "tensorflow/core/profiler/lib/traceme.h"
17
18 namespace tensorflow {
19 namespace profiler {
20
21 // Activity IDs: To avoid contention over a counter, the top 32 bits identify
22 // the originating thread, the bottom 32 bits name the event within a thread.
23 // IDs may be reused after 4 billion events on one thread, or 4 billion threads.
24 static std::atomic<uint32> thread_counter(1); // avoid kUntracedActivity
NewActivityId()25 uint64 NewActivityId() {
26 const thread_local static uint32 thread_id = thread_counter.fetch_add(1);
27 thread_local static uint32 per_thread_activity_id = 0;
28 return static_cast<uint64>(thread_id) << 32 | per_thread_activity_id++;
29 }
30
ActivityStartImpl(absl::string_view activity_name)31 /* static */ uint64 TraceMe::ActivityStartImpl(
32 absl::string_view activity_name) {
33 uint64 activity_id = NewActivityId();
34 TraceMeRecorder::Record({activity_id, string(activity_name),
35 /*start_time=*/Env::Default()->NowNanos(),
36 /*end_time=*/0});
37 return activity_id;
38 }
39
ActivityEndImpl(uint64 activity_id)40 /* static */ void TraceMe::ActivityEndImpl(uint64 activity_id) {
41 TraceMeRecorder::Record({activity_id, /*name=*/"", /*start_time=*/0,
42 /*end_time=*/Env::Default()->NowNanos()});
43 }
44
45 } // namespace profiler
46 } // namespace tensorflow
47