追蹤程式庫

如要進行追蹤,您可以使用下列程式庫:

libtrace-provider:追蹤提供者程式庫

這個程式庫提供 C 和 C++ 函式,可使用 Fuchsia 追蹤系統註冊程序的追蹤引擎。為了讓追蹤功能在程序中正常運作,您必須在執行期間的某個時間點初始化追蹤記錄提供者。此外,您也可以實作自己的追蹤處理常式,以其他方式註冊追蹤記錄引擎。

追蹤程式需要非同步調度程式才能運作。

C++

#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <trace-provider/provider.h>

int main(int argc, char** argv) {
  // Create a message loop.
   async::Loop loop(&kAsyncLoopConfigNoAttachToCurrentThread);

  // Start a thread for the loop to run on.
  // Alternatively, you could use async_loop_run() to run on the current thread.
  zx_status_t status = loop.StartThread();
  if (status != ZX_OK) exit(1);

  // Create the trace provider.
  trace::TraceProviderWithFdio trace_provider(loop.dispatcher());

  // Do something...

  // The loop and trace provider will shut down once the scope exits.
  return 0;
}

C 調

#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <trace-provider/provider.h>

int main(int argc, char** argv) {
  zx_status_t status;
  async_loop_t* loop;
  trace_provider_t* trace_provider;

  // Create a message loop.
  status = async_loop_create(&kAsyncLoopConfigNoAttachToCurrentThread, &loop);
  if (status != ZX_OK) exit(1);

  // Start a thread for the loop to run on.
  // Alternatively, use async_loop_run() to run on the current thread.
  status = async_loop_start_thread(loop, "loop", NULL);
  if (status != ZX_OK) exit(1);

  // Create the trace provider.
  async_dispatcher_t* dispatcher = async_loop_get_dispatcher(loop);
  trace_provider = trace_provider_create(dispatcher);
  if (!trace_provider) exit(1);

  // Do something...

  // Tear down.
  trace_provider_destroy(trace_provider);
  async_loop_shutdown(loop);
  return 0;
}

libtrace:C 和 C++ 追蹤事件程式庫

這個程式庫提供巨集和內嵌函式,可用來檢測 C 和 C++ 程式,並提供追蹤點,用來在追蹤執行期間擷取追蹤記錄資料。

請參閱「//zircon/system/ulib/trace/include/lib/trace/event.h」。

C++

這個範例會記錄標示 DoSomething 函式開始與結束及其參數的追蹤事件。

#include <trace/event.h>

void DoSomething(int a, std::string b) {
  TRACE_DURATION("example", "DoSomething", "a", a, "b", b);

  // Do something
}

C 調

這個範例會記錄標示 DoSomething 函式開始與結束及其參數的追蹤事件。

與 C++ 不同的是,您必須指定每個追蹤記錄引數的類型。C++ 支援這類註解,但由於編譯器可以推論類型本身,因此不一定要使用註解。

#include <trace/event.h>

void DoSomething(int a, const char* b) {
  TRACE_DURATION("example", "DoSomething", "a", TA_INT32(a), "b", TA_STRING(b));

  // Do something
}

在編譯單位內抑制追蹤記錄

如要完全抑制編譯單位中的追蹤功能,請先定義 NTRACE 巨集,再加入追蹤標頭。這會導致巨集的行為如同一律停用追蹤功能一樣,因此不會產生追蹤記錄,也就不會產生執行階段負擔。

#define NTRACE
#include <trace/event.h>

void DoSomething(void) {
  // This will never produce trace records because the NTRACE macro was
  // defined above.
  TRACE_DURATION("example", "DoSomething");
}

libtrace-reader:追蹤讀取器程式庫

這個程式庫提供 C++ 類型和函式,方便您讀取追蹤記錄封存資料。

請參閱「//zircon/system/ulib/trace-reader/include/trace-reader/reader.h」。