Skip to main content
gamedev.net
🔒 Locked

memcpy

Started by Doomrat 2 replies 250+ views
Original Post
Doomrat
Doomrat
Is this function usually as fast as you could hope for without writing a custom asm routine?
Alimonster
Alimonster
Well, here's a test program:

  #include <cstring>

int main()
{
int a[40];
int b[40];
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));

memcpy(a, b, sizeof(a));

for (int index = 0; index < 40; ++index)
{
if (a[index] != b[index])
return - 1;
}

return 0;
}

(Note that the for loop is there so the entire main function isn't snipped out while optimising(!)):
	TITLE	C:\My Documents\Programs\C++\testBits\main.cpp
.386P
include listing.inc
if @Version gt 510
.model FLAT
else
_TEXT SEGMENT PARA USE32 PUBLIC 'CODE'
_TEXT ENDS
_DATA SEGMENT DWORD USE32 PUBLIC 'DATA'
_DATA ENDS
CONST SEGMENT DWORD USE32 PUBLIC 'CONST'
CONST ENDS
_BSS SEGMENT DWORD USE32 PUBLIC 'BSS'
_BSS ENDS
_TLS SEGMENT DWORD USE32 PUBLIC 'TLS'
_TLS ENDS
; COMDAT _main
_TEXT SEGMENT PARA USE32 PUBLIC 'CODE'
_TEXT ENDS
FLAT GROUP _DATA, CONST, _BSS
ASSUME CS: FLAT, DS: FLAT, SS: FLAT
endif
PUBLIC _main
; COMDAT _main
_TEXT SEGMENT
_a$ = -160
_b$ = -320
_main PROC NEAR ; COMDAT

; 3 : {

sub esp, 320 ; 00000140H

; 4 : int a[40];
; 5 : int b[40];
; 6 : memset(a, 0, sizeof(a));
; 7 : memset(b, 0, sizeof(b));

mov ecx, 40 ; 00000028H
xor eax, eax
push esi
push edi
lea edi, DWORD PTR _b$[esp+328]

; 8 :
; 9 : memcpy(a, b, sizeof(a));

lea esi, DWORD PTR _b$[esp+328]
rep stosd
mov ecx, 40 ; 00000028H
lea edi, DWORD PTR _a$[esp+328]
rep movsd
$L485:

; 10 :
; 11 : for (int index = 0; index < 40; ++index)
; 12 : {
; 13 : if (a[index] != b[index])

mov ecx, DWORD PTR _a$[esp+eax+328]
mov esi, DWORD PTR _b$[esp+eax+328]
cmp ecx, esi
jne SHORT $L494
add eax, 4
cmp eax, 160 ; 000000a0H
jl SHORT $L485
pop edi

; 15 : }
; 16 :
; 17 : return 0;

xor eax, eax
pop esi

; 18 : }

add esp, 320 ; 00000140H
ret 0
$L494:
pop edi

; 14 : return - 1;

or eax, -1
pop esi

; 18 : }

add esp, 320 ; 00000140H
ret 0
_main ENDP
_TEXT ENDS
END

That's the generated asm in the default Release mode settings. I'm sure it means something to someone...

It seems that rep stosd is being used. I remember reading somewhere that newer processors prefer simpler instructions instead, but stosd will probably perform fine here. I'm not an assembly guru, though, so that info may be somehow wrong...

[edited by - Alimonster on May 26, 2002 6:57:34 AM]
Dean Harding
Dean Harding
memcpy is usually implemented in assembly anyway (at least for MSVC++ it is) and it''s probably as fast as you''ll get it (copying in DWORDs wherever possible, etc).

Besides, I don''t think memcpy is your bottleneck (unless you can prove it to me with a profiler).


codeka.com - Just click it.
Doomrat
Doomrat
Thanks guys, that''s exactly what I needed to know.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.