aperf.c 1.7 KB

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