0001
0002 #include <math.h>
0003 #include <unistd.h>
0004 #include <stdio.h>
0005 #include <stdlib.h>
0006 #include <sys/types.h>
0007 #include <sys/stat.h>
0008 #include <fcntl.h>
0009 #include <sys/timeb.h>
0010 #include <sched.h>
0011 #include <errno.h>
0012 #include <string.h>
0013 #include <time.h>
0014 #include "../kselftest.h"
0015
0016 #define MSEC_PER_SEC 1000L
0017 #define NSEC_PER_MSEC 1000000L
0018
0019 void usage(char *name) {
0020 printf ("Usage: %s cpunum\n", name);
0021 }
0022
0023 int main(int argc, char **argv) {
0024 unsigned int i, cpu, fd;
0025 char msr_file_name[64];
0026 long long tsc, old_tsc, new_tsc;
0027 long long aperf, old_aperf, new_aperf;
0028 long long mperf, old_mperf, new_mperf;
0029 struct timespec before, after;
0030 long long int start, finish, total;
0031 cpu_set_t cpuset;
0032
0033 if (argc != 2) {
0034 usage(argv[0]);
0035 return 1;
0036 }
0037
0038 errno = 0;
0039 cpu = strtol(argv[1], (char **) NULL, 10);
0040
0041 if (errno) {
0042 usage(argv[0]);
0043 return 1;
0044 }
0045
0046 sprintf(msr_file_name, "/dev/cpu/%d/msr", cpu);
0047 fd = open(msr_file_name, O_RDONLY);
0048
0049 if (fd == -1) {
0050 printf("/dev/cpu/%d/msr: %s\n", cpu, strerror(errno));
0051 return KSFT_SKIP;
0052 }
0053
0054 CPU_ZERO(&cpuset);
0055 CPU_SET(cpu, &cpuset);
0056
0057 if (sched_setaffinity(0, sizeof(cpu_set_t), &cpuset)) {
0058 perror("Failed to set cpu affinity");
0059 return 1;
0060 }
0061
0062 if (clock_gettime(CLOCK_MONOTONIC, &before) < 0) {
0063 perror("clock_gettime");
0064 return 1;
0065 }
0066 pread(fd, &old_tsc, sizeof(old_tsc), 0x10);
0067 pread(fd, &old_aperf, sizeof(old_mperf), 0xe7);
0068 pread(fd, &old_mperf, sizeof(old_aperf), 0xe8);
0069
0070 for (i=0; i<0x8fffffff; i++) {
0071 sqrt(i);
0072 }
0073
0074 if (clock_gettime(CLOCK_MONOTONIC, &after) < 0) {
0075 perror("clock_gettime");
0076 return 1;
0077 }
0078 pread(fd, &new_tsc, sizeof(new_tsc), 0x10);
0079 pread(fd, &new_aperf, sizeof(new_mperf), 0xe7);
0080 pread(fd, &new_mperf, sizeof(new_aperf), 0xe8);
0081
0082 tsc = new_tsc-old_tsc;
0083 aperf = new_aperf-old_aperf;
0084 mperf = new_mperf-old_mperf;
0085
0086 start = before.tv_sec*MSEC_PER_SEC + before.tv_nsec/NSEC_PER_MSEC;
0087 finish = after.tv_sec*MSEC_PER_SEC + after.tv_nsec/NSEC_PER_MSEC;
0088 total = finish - start;
0089
0090 printf("runTime: %4.2f\n", 1.0*total/MSEC_PER_SEC);
0091 printf("freq: %7.0f\n", tsc / (1.0*aperf / (1.0 * mperf)) / total);
0092 return 0;
0093 }