os_info.h 2.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#pragma once

L
liutiexing 已提交
17
#include <string>
18 19 20 21
#include <unordered_map>
#ifdef _POSIX_C_SOURCE
#include <time.h>
#endif
L
liutiexing 已提交
22
#include "paddle/fluid/platform/port.h"
23 24 25 26

namespace paddle {
namespace platform {

L
liutiexing 已提交
27
// Get system-wide realtime clock in nanoseconds
28 29 30 31 32 33 34 35 36 37 38 39 40
inline uint64_t PosixInNsec() {
#ifdef _POSIX_C_SOURCE
  struct timespec tp;
  clock_gettime(CLOCK_REALTIME, &tp);
  return tp.tv_sec * 1000 * 1000 * 1000 + tp.tv_nsec;
#else
  struct timeval tv;
  gettimeofday(&tv, nullptr);
  return 1000 * (static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec);
#endif
}

// All kinds of Ids for OS thread
L
liutiexing 已提交
41 42 43 44 45
struct ThreadId {
  uint64_t std_tid = 0;    // std::hash<std::thread::id>
  uint64_t sys_tid = 0;    // OS-specific, Linux: gettid
  uint32_t cupti_tid = 0;  // thread_id used by Nvidia CUPTI
};
46

L
liutiexing 已提交
47 48
// Better performance than GetCurrentThreadId
uint64_t GetCurrentThreadStdId();
49

L
liutiexing 已提交
50 51
// Better performance than GetCurrentThreadId
uint64_t GetCurrentThreadSysId();
52

L
liutiexing 已提交
53
ThreadId GetCurrentThreadId();
54

L
liutiexing 已提交
55 56 57 58
// Return the map from StdTid to ThreadId
// Returns current snapshot of all threads. Make sure there is no thread
// create/destory when using it.
std::unordered_map<uint64_t, ThreadId> GetAllThreadIds();
59

L
liutiexing 已提交
60 61
// Returns 'unset' if SetCurrentThreadName is never called.
std::string GetCurrentThreadName();
62

L
liutiexing 已提交
63 64 65 66 67 68 69 70 71 72
// Return the map from StdTid to ThreadName
// Returns current snapshot of all threads. Make sure there is no thread
// create/destory when using it.
std::unordered_map<uint64_t, std::string> GetAllThreadNames();

// Thread name is immutable, only the first call will succeed.
// Returns false on failure.
bool SetCurrentThreadName(const std::string& name);

uint32_t GetProcessId();
73 74 75

}  // namespace platform
}  // namespace paddle