aperf.c 1.8 KB

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