代码如下:
#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>
#define PGSIZE 4096
//return us
int time_diff(struct timeval* t1, struct timeval* t2) {
return (t2->tv_sec - t1->tv_sec) * 1000000 + (t2->tv_usec - t1->tv_usec);
}
int main(int argc, char* argv[]) {
if (argc != 3) {
fprintf(stderr, "too many or too few arguments\n");
exit(1);
}
int i;
int pageCount = atoi(argv[1]);
int num = atoi(argv[2]);
struct timeval curr, now;
int size = (pageCount * PGSIZE) / sizeof(int);
int arr[size];
if (gettimeofday(&curr, NULL) == -1) {
fprintf(stderr, "gettimeofday error\n");
exit(1);
}
for (i = 0; i < num; ++i) {
arr[(rand() % pageCount) * (PGSIZE / sizeof(int))] = i;
}
if (gettimeofday(&now, NULL) != 0) {
fprintf(stderr, "gettimeofday error\n");
exit(1);
}
printf("time elaps %d us\n", time_diff(&curr, &now));
return 0;
}
运行结果如下:
100000次访问消耗1230us,平均每次访问时间为12.3ns