Copying bytes without memcpy

人走茶凉 提交于 2020-01-04 14:58:10

问题


I have several variables of different types stored in a char array. Normally I would write them to the array this way:

int a = 5;
memcpy(offset, (char*)&a, sizeof(int))

However, memcpy doesn't work in OpenCL kernels. What would be the easiest way to do the same without this function?


回答1:


You can easily enough provide mymemcpy

  void mymemcpy(unsigned char *dest, const unsigned char *src, size_t N)
  {
     size_t i;

     for(i=0;i<N;i++)
       dest[i] = src[i];
  }

However it's not very efficient because most copies are aligned copies of multiples of 4 or 8 bytes. If you can work out that alignment is 8 bytes, copy in units of unsigned long long. Sometimes it's even worth padding a buffer to bring it up to a multiple of 8 bytes.




回答2:


How about a loop?

int a;
unsigned char * p = (unsigned char *)&a;
for (int i = 0; i != sizeof(int); ++i) offset[i] = p[i];



回答3:


You can use vload and vstore commands for just 1-16 bytes for char type and 4-64 bytes for int type and 8-128 bytes for long type. This could be advantageous or disadvantageous depending on the total cores' memory accessing patterns.

I didnt check but this should trigger a compiler to use fast sse avx load and store on a cpu and use full bus width for gpu. Also alignment conditions are met because it is uhdesinde behaviour for unaligned accessing with load store.

You need to copy non aligned head part of array first. If there is any .



来源:https://stackoverflow.com/questions/42823726/copying-bytes-without-memcpy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!