Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Verifying on Memory behavior
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#define LENGTH (512UL*1024*1024)
#define INTERVAL 10
void print_time(char *buf){
struct timespec ts;
struct tm tm;
clock_gettime(CLOCK_REALTIME, &ts);
localtime_r( &ts.tv_sec, &tm);
printf("%d/%02d/%02d %02d:%02d:%02d.%06ld: %s\n",
tm.tm_year+1900,
tm.tm_mon+1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec,
ts.tv_nsec/1000,
buf);
return;
}
static void check_bytes(char *addr)
{
printf("First hex is %x\n", *((unsigned int *)addr));
}
static void write_bytes(char *addr)
{
unsigned long i,count,point;
point = LENGTH / 20;
count = 0;
for (i = 0; i < LENGTH; i++){
*(addr + i) = (unsigned int)i;
count++;
if( count >= point ){
sleep(1);
count=0;
}
}
return;
}
static int read_bytes(char *addr)
{
unsigned long i,count,point;
point = LENGTH / 20;
count = 0;
check_bytes(addr);
for (i = 0; i < LENGTH; i++){
(void)(addr + i);
count++;
if( count >= point ){
sleep(1);
count=0;
}
}
return 0;
}
int main(void)
{
void *addr;
int ret;
print_time("upped the test program");
sleep(INTERVAL);
print_time("step1 get virtual memory via malloc");
addr = malloc(LENGTH);
if (addr == NULL ) {
perror("malloc");
exit(1);
}
printf("Returned address is %p\n", addr);
check_bytes(addr);
sleep(INTERVAL);
print_time("step2 start reading");
ret = read_bytes(addr);
print_time("step2 finish reading");
sleep(INTERVAL);
print_time("step3 start writing");
write_bytes(addr);
print_time("step3 finish writing");
sleep(INTERVAL);
print_time("step4 start reading");
ret = read_bytes(addr);
print_time("step4 finish reading");
/* munmap() length of MAP_HUGETLB memory must be hugepage aligned */
sleep(INTERVAL);
print_time("step5 free");
free(addr);
sleep(INTERVAL);
print_time("quit the test promgram");
return ret;
}
@pasear

This comment has been minimized.

Copy link

pasear commented May 16, 2019

I come from the page http://nopipi.hatenablog.com/entry/2017/11/11/213214 to see how you have implemented the tests.
It seems that your read_bytes() wouldn't work.
59 (void)(addr + i);
This has no effect at all. It does not read and is simply pointer arithmetic.
Also, it is highly likely to be be dropped by GCC and you should turn off the optimization or check the assembly, too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.