aperf.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <math.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9. #include <sys/timeb.h>
  10. #include <sched.h>
  11. #include <errno.h>
  12. void usage(char *name) {
  13. printf ("Usage: %s cpunum\n", name);
  14. }
  15. int main(int argc, char **argv) {
  16. unsigned int i, cpu, fd;
  17. char msr_file_name[64];
  18. long long tsc, old_tsc, new_tsc;
  19. long long aperf, old_aperf, new_aperf;
  20. long long mperf, old_mperf, new_mperf;
  21. struct timeb before, after;
  22. long long int start, finish, total;
  23. cpu_set_t cpuset;
  24. if (argc != 2) {
  25. usage(argv[0]);
  26. return 1;
  27. }
  28. errno = 0;
  29. cpu = strtol(argv[1], (char **) NULL, 10);
  30. if (errno) {
  31. usage(argv[0]);
  32. return 1;
  33. }
  34. sprintf(msr_file_name, "/dev/cpu/%d/msr", cpu);
  35. fd = open(msr_file_name, O_RDONLY);
  36. if (fd == -1) {
  37. perror("Failed to open");
  38. return 1;
  39. }
  40. CPU_ZERO(&cpuset);
  41. CPU_SET(cpu, &cpuset);
  42. if (sched_setaffinity(0, sizeof(cpu_set_t), &cpuset)) {
  43. perror("Failed to set cpu affinity");
  44. return 1;
  45. }
  46. ftime(&before);
  47. pread(fd, &old_tsc, sizeof(old_tsc), 0x10);
  48. pread(fd, &old_aperf, sizeof(old_mperf), 0xe7);
  49. pread(fd, &old_mperf, sizeof(old_aperf), 0xe8);
  50. for (i=0; i<0x8fffffff; i++) {
  51. sqrt(i);
  52. }
  53. ftime(&after);
  54. pread(fd, &new_tsc, sizeof(new_tsc), 0x10);
  55. pread(fd, &new_aperf, sizeof(new_mperf), 0xe7);
  56. pread(fd, &new_mperf, sizeof(new_aperf), 0xe8);
  57. tsc = new_tsc-old_tsc;
  58. aperf = new_aperf-old_aperf;
  59. mperf = new_mperf-old_mperf;
  60. start = before.time*1000 + before.millitm;
  61. finish = after.time*1000 + after.millitm;
  62. total = finish - start;
  63. printf("runTime: %4.2f\n", 1.0*total/1000);
  64. printf("freq: %7.0f\n", tsc / (1.0*aperf / (1.0 * mperf)) / total);
  65. return 0;
  66. }