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 (64UL*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(unsigned long *addr)
{
printf("First hex is %x\n", *((unsigned long *)addr));
}
static void write_bytes(unsigned long *addr)
{
unsigned long i,count,point;
point = LENGTH / 20;
count = 0;
for (i = 0; i < LENGTH; i++){
*(addr + i) = (unsigned long)i;
//printf("i=%10lu \n",i);
count++;
if( count >= point ){
sleep(1);
count=0;
}
}
return;
}
static int read_bytes(unsigned long *addr)
{
unsigned long i,count,point,dummy;
point = LENGTH / 20;
count = 0;
check_bytes(addr);
for (i = 0; i < LENGTH; i++){
dummy = (unsigned long)*(addr + i);
//printf("i=%10lu dummy=%10lu\n",i, dummy);
count++;
if( count >= point ){
sleep(1);
count=0;
}
}
return 0;
}
int main(void)
{
unsigned long *addr;
int ret;
print_time("upped the test program");
sleep(INTERVAL);
print_time("step1 get virtual memory via malloc");
addr = malloc(LENGTH * sizeof(unsigned long) );
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 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.

@Noppy

This comment has been minimized.

Copy link
Owner Author

@Noppy Noppy commented May 17, 2020

Pasear,
Thanks for your advice.
I have also confirmed that read_bytes function does not read too.
Therefore, I fixed the program.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment