aperf.c 2.1 KB

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