main.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include <stdio.h>
  2. #include <inttypes.h>
  3. #include <stdint.h>
  4. #include <stdlib.h>
  5. #include <getopt.h>
  6. #include <string.h>
  7. #include <errno.h>
  8. const char* smaps_file = "smaps";
  9. bool verbose = false;
  10. int iterations = 1;
  11. int bufsz = -1;
  12. int64_t
  13. get_pss(int pid)
  14. {
  15. char filename[64];
  16. snprintf(filename, sizeof(filename), "/proc/%" PRId32 "/%s", pid,
  17. smaps_file);
  18. if (verbose)
  19. fprintf(stderr, "smaps:[%s]\n", filename);
  20. FILE * file = fopen(filename, "r");
  21. if (!file) {
  22. return (int64_t) -1;
  23. }
  24. if (bufsz >= 0) {
  25. if (setvbuf(file, NULL, _IOFBF, bufsz)) {
  26. fprintf(stderr, "setvbuf failed: %s\n", strerror(errno));
  27. exit(1);
  28. }
  29. }
  30. // Tally up all of the Pss from the various maps
  31. char line[256];
  32. int64_t pss = 0;
  33. while (fgets(line, sizeof(line), file)) {
  34. int64_t v;
  35. if (sscanf(line, "Pss: %" SCNd64 " kB", &v) == 1) {
  36. if (verbose)
  37. fprintf(stderr, "pss line: %llu\n", (unsigned long long) v);
  38. pss += v;
  39. }
  40. }
  41. fclose(file);
  42. // Return the Pss value in bytes, not kilobytes
  43. return pss * 1024;
  44. }
  45. int
  46. main(int argc, char** argv)
  47. {
  48. int c;
  49. while ((c = getopt(argc, argv, "n:rvb:")) != -1) {
  50. switch (c) {
  51. case 'r':
  52. smaps_file = "smaps_rollup";
  53. break;
  54. case 'v':
  55. verbose = true;
  56. break;
  57. case 'n':
  58. iterations = atoi(optarg);
  59. break;
  60. case 'b':
  61. bufsz = atoi(optarg);
  62. break;
  63. default:
  64. return 1;
  65. }
  66. }
  67. if (argv[optind] == NULL) {
  68. fprintf(stderr, "pssbench: no PID given\n");
  69. return 1;
  70. }
  71. int pid = atoi(argv[optind]);
  72. int64_t pss = 0;
  73. for (int i = 0; i < iterations; ++i)
  74. pss = get_pss(pid);
  75. fflush(NULL);
  76. printf("iterations:%d pid:%d pss:%lld\n", iterations, pid, (long long)pss);
  77. return 0;
  78. }