2
0

cpu_profiler.cc 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // Copyright (c) 2013-2021 Winlin
  3. //
  4. // SPDX-License-Identifier: MIT
  5. //
  6. /**
  7. @see: https://gperftools.github.io/gperftools/cpuprofile.html
  8. config srs with gperf(to make gperftools):
  9. ./configure --with-gperf --jobs=3
  10. set the pprof path if not set:
  11. export PPROF_PATH=`pwd`/../../../objs/pprof
  12. to do cpu profile:
  13. make && rm -f ./srs.prof* && env CPUPROFILE=./srs.prof ./cpu_profiler
  14. $PPROF_PATH --text cpu_profiler ./srs.prof*
  15. to do cpu profile by signal:
  16. make && rm -f ./srs.prof* && env CPUPROFILE=./srs.prof CPUPROFILESIGNAL=12 ./cpu_profiler
  17. $PPROF_PATH --text cpu_profiler ./srs.prof*
  18. */
  19. #include <stdio.h>
  20. #include <unistd.h>
  21. #include <signal.h>
  22. #include <stdlib.h>
  23. #include <gperftools/profiler.h>
  24. void cpu_profile_imp() {
  25. for (int i = 0; i < 2; ++i) {
  26. for (int j = 0; j < 110 * 1024 * 1024; ++j) {
  27. }
  28. printf("cpu profile, loop 110M\n");
  29. printf("press CTRL+C if you want to abort the program.\n");
  30. sleep(3);
  31. }
  32. }
  33. void cpu_profile() {
  34. cpu_profile_imp();
  35. }
  36. void handler(int sig) {
  37. exit(0);
  38. }
  39. int main(int argc, char** argv) {
  40. signal(SIGINT, handler);
  41. // must start profiler manually.
  42. ProfilerStart(NULL);
  43. if (getenv("CPUPROFILESIGNAL")) {
  44. printf("if specified CPUPROFILESIGNAL, use signal to active it: kill -12 %d\n", getpid());
  45. sleep(3);
  46. }
  47. cpu_profile();
  48. // not neccessary to call stop.
  49. //ProfilerStop();
  50. return 0;
  51. }