User avatar
DavidS
Posts: 4334
Joined: Thu Dec 15, 2011 6:39 am
Location: USA
Contact: Website

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Mon Jul 22, 2019 8:21 pm

MySelf wrote:And the criticism I get is, why did I use Assembly Language. There are plenty of other things that people could criticize about that code, though they ignore all the other stuff, and target my choice to use a little bit of assembly language.
I should actually elaborate on that a touch, as the wording may make it sound wrong.

It is ok to critisize the use of assembly language. The problem is that many people were not looking at the code and essensially saying 'no one should ever use assembly language', and things of that like, ignoring the content of the code completely.

And a lot of people did such things. A few even called me names for using assembly language.

The badgering against assembly language whent on for multiple pages, without any comments about the code I had posted.
RPi = The best ARM based RISC OS computer around
More than 95% of posts made from RISC OS on RPi 1B/1B+ computers. Most of the rest from RISC OS on RPi 2B/3B/3B+ computers

Musketeer
Posts: 152
Joined: Fri Feb 12, 2016 1:23 pm
Location: CZ

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Mon Jul 22, 2019 8:31 pm

DavidS wrote:
Mon Jul 22, 2019 8:21 pm
MySelf wrote:And the criticism I get is, why did I use Assembly Language. There are plenty of other things that people could criticize about that code, though they ignore all the other stuff, and target my choice to use a little bit of assembly language.
I should actually elaborate on that a touch, as the wording may make it sound wrong.

It is ok to critisize the use of assembly language. The problem is that many people were not looking at the code and essensially saying 'no one should ever use assembly language', and things of that like, ignoring the content of the code completely.

And a lot of people did such things. A few even called me names for using assembly language.

The badgering against assembly language whent on for multiple pages, without any comments about the code I had posted.
If you are average USA kid from high school that is not so bad as it seems in news! :idea:
Linux is like woman - both wants 180 % of your time...
You want speed Java 9.8x? Throw it out of some Window(s)!
My girlfriend is terribly unmature - she always sinks my boats in bathtub!

User avatar
DavidS
Posts: 4334
Joined: Thu Dec 15, 2011 6:39 am
Location: USA
Contact: Website

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Mon Jul 22, 2019 8:46 pm

Musketeer wrote:
Mon Jul 22, 2019 8:31 pm
If you are average USA kid from high school that is not so bad as it seems in news! :idea:
LOL. Far from that. I only ever attended private institutions, as I was always way to far ahead of my grade level do to studdying at home. Then I went to university, then to another for post grad, and that was all before 1997.

Never even paid attention in school at that. I always studdied independantly, and passed any exams. Then in Post Grad independant study is encouraged, so I did so. After I submitted my second thesis I gave up on schools (mostely because I do not think I would make a good professor, and that is what they wanted of me).


The issue can be seen in that I can not get people on a forum to actually look at code, because they are to bussy bashing the use of assembly. Kind of makes it a waste of time to post code at all, do you think?
RPi = The best ARM based RISC OS computer around
More than 95% of posts made from RISC OS on RPi 1B/1B+ computers. Most of the rest from RISC OS on RPi 2B/3B/3B+ computers

Musketeer
Posts: 152
Joined: Fri Feb 12, 2016 1:23 pm
Location: CZ

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Mon Jul 22, 2019 8:50 pm

I sense lot of opportunities... :ugeek:
Linux is like woman - both wants 180 % of your time...
You want speed Java 9.8x? Throw it out of some Window(s)!
My girlfriend is terribly unmature - she always sinks my boats in bathtub!

User avatar
Michiel O.
Posts: 178
Joined: Mon Dec 12, 2016 12:06 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Mon Jul 22, 2019 10:49 pm

DavidS wrote: There are plenty of other things that people could criticize about that code.
First and foremost, I was surprised about your implementation of strcpy, since I heard you praising the benefits of pointers on multiple occasions. Yet, you use an extra index variable and array notation:

Code: Select all

char *StrCpyDavid(char *s, char *t){
    for(int cnt = 0; (s[cnt] = t[cnt]); cnt++);
    return s;
    }
My suggestion is to use pointers for strcpy:

Code: Select all

char *StrCpyMichiel(char *dst, char *src) {
    char *d = dst;
    while (*dst++ = *src++);
    return d;
    }
Not only is this more in the spirit of C, but it's also quite a lot more efficient:

$ cc strcpy.c && ./a.out # timed on a RPi3B
David took 11287 microseconds
Michiel took 7603 microseconds


Furthermore, I find ARM assembly beautiful. It has a blend of nostalgia and esthetic pleasure for me. Nostalgia, because the 6502 was the first CPU I learned to program in machine language on, and that CPU leaned towards RISC, in contrast to the Z80). Later the 68000 family came along in the same flavour. And that all culminated in the ARM instruction set, which is nicely orthogonal, unlike the CISC x86/amd64 architecture.

Code: Select all

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

char *StrCpyDavid(char *s, char *t){
    for(int cnt = 0; (s[cnt] = t[cnt]); cnt++);
    return s;
    }

char *StrCpyMichiel(char *dst, char *src) {
    char *d = dst;
    while (*dst++ = *src++);
    return d;
    }

// Get current time in microseconds
unsigned long usec(){
    struct timeval currentTime;
    gettimeofday(&currentTime, NULL);
    return currentTime.tv_sec * (int)1e6 + currentTime.tv_usec;
    }

int main(void) {
    char from[] = "Hello, world! How are you? I'm find, thanks! This is just a test string.";
    char to[80];

    unsigned long start = usec();
    for (int i=0; i<10000; i++)
        StrCpyDavid(to, from);
    unsigned long dur = usec() - start;
    printf("David took %lu microseconds\n", dur);

    start = usec();
    for (int i=0; i<10000; i++)
        StrCpyMichiel(to, from);
    dur = usec() - start;
    printf("Michiel took %lu microseconds\n", dur);
    }
"You can't actually make computers run faster, you can only make them do less." - RiderOfGiraffes

User avatar
DavidS
Posts: 4334
Joined: Thu Dec 15, 2011 6:39 am
Location: USA
Contact: Website

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 12:57 am

Michiel O. wrote:
Mon Jul 22, 2019 10:49 pm
DavidS wrote: There are plenty of other things that people could criticize about that code.
First and foremost,
Thank you for actually looking at the code, finaly someone does, that is encouraging.
I was surprised about your implementation of strcpy, since I heard you praising the benefits of pointers on multiple occasions. Yet, you use an extra index variable and array notation:

Code: Select all

char *StrCpyDavid(char *s, char *t){
    for(int cnt = 0; (s[cnt] = t[cnt]); cnt++);
    return s;
    }
My suggestion is to use pointers for strcpy:

Code: Select all

char *StrCpyMichiel(char *dst, char *src) {
    char *d = dst;
    while (*dst++ = *src++);
    return d;
    }
Not only is this more in the spirit of C, but it's also quite a lot more efficient:
Agreed. One thing I often will do for a simple string copy is to not use a function call at all, though rather where the copy is done:

Code: Select all

while(*dst++=*src++);
Preserving pointers if needed.

I did not think that one well the morning I threw that code together, in reply to a question on the forums (about two or 3 years ago).

$ cc strcpy.c && ./a.out # timed on a RPi3B
David took 11287 microseconds
Michiel took 7603 microseconds


Furthermore, I find ARM assembly beautiful. It has a blend of nostalgia and esthetic pleasure for me. Nostalgia, because the 6502 was the first CPU I learned to program in machine language on, and that CPU leaned towards RISC, in contrast to the Z80). Later the 68000 family came along in the same flavour. And that all culminated in the ARM instruction set, which is nicely orthogonal, unlike the CISC x86/amd64 architecture.

Code: Select all

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

char *StrCpyDavid(char *s, char *t){
    for(int cnt = 0; (s[cnt] = t[cnt]); cnt++);
    return s;
    }

char *StrCpyMichiel(char *dst, char *src) {
    char *d = dst;
    while (*dst++ = *src++);
    return d;
    }

// Get current time in microseconds
unsigned long usec(){
    struct timeval currentTime;
    gettimeofday(&currentTime, NULL);
    return currentTime.tv_sec * (int)1e6 + currentTime.tv_usec;
    }

int main(void) {
    char from[] = "Hello, world! How are you? I'm find, thanks! This is just a test string.";
    char to[80];

    unsigned long start = usec();
    for (int i=0; i<10000; i++)
        StrCpyDavid(to, from);
    unsigned long dur = usec() - start;
    printf("David took %lu microseconds\n", dur);

    start = usec();
    for (int i=0; i<10000; i++)
        StrCpyMichiel(to, from);
    dur = usec() - start;
    printf("Michiel took %lu microseconds\n", dur);
    }
Thank you for that.

I am glad to see someone actually look at my code.

I am also happy to see someone else that likes Assembly Language (and notes the problems with the most common CISC assembly language today).
RPi = The best ARM based RISC OS computer around
More than 95% of posts made from RISC OS on RPi 1B/1B+ computers. Most of the rest from RISC OS on RPi 2B/3B/3B+ computers

User avatar
Michiel O.
Posts: 178
Joined: Mon Dec 12, 2016 12:06 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 2:06 am

DavidS wrote: I am also happy to see someone else that likes Assembly Language
Yes. And as fine purveyors of the inline variant, lets write strcpy in assembly inside the C code:

Code: Select all

void StrCpyAsm(char *dst, const char *src)
{
__asm__(
    "loop: \n"
    "     ldrb  r2, [r1], #1 \n"
    "     strb  r2, [r0], #1 \n"
    "     cmp   r2, #0 \n"
    "     bne   loop \n"
    );
}
It performs three times faster than the C pointer version:

$ ./a.out
David took 22585 microseconds
Michiel took 15357 microseconds
Asm took 4180 microseconds


I suspect it can even be more optimized:

• The version above still does a C calling frame setup and teardown, I think that can be substituted for a simple register push and pop. That probably requires StrCpyAsm in its own pure assembly file, strcpyasm.s, and compiling/linking it in.

• Moving strings a whole register at a time (4 or 8 characters, depending on architecture) as much as possible. Lots of corner cases here with alignment issues!

Code: Select all

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

char *StrCpyDavid(char *s, char *t){
    for(int cnt = 0; (s[cnt] = t[cnt]); cnt++);
    return s;
    }

char *StrCpyMichiel(char *dst, char *src) {
    char *d = dst;
    while (*dst++ = *src++);
    return d;
    }

void StrCpyAsm(char *dst, const char *src)
{
__asm__(
    "loop: \n"
    "     ldrb  r2, [r1], #1 \n"
    "     strb  r2, [r0], #1 \n"
    "     cmp   r2, #0 \n"
    "     bne   loop \n"
    );
}

// Get current time in microseconds
unsigned long usec(){
    struct timeval currentTime;
    gettimeofday(&currentTime, NULL);
    return currentTime.tv_sec * (int)1e6 + currentTime.tv_usec;
    }

int main(void) {
    char from[] = "Hello, world! How are you? I'm find, thanks! This is just a test string.";
    char to[80];

    unsigned long start = usec();
    for (int i=0; i<10000; i++)
        StrCpyDavid(to, from);
    unsigned long dur = usec() - start;
    printf("David took %lu microseconds\n", dur);

    start = usec();
    for (int i=0; i<10000; i++)
        StrCpyMichiel(to, from);
    dur = usec() - start;
    printf("Michiel took %lu microseconds\n", dur);

    start = usec();
    for (int i=0; i<10000; i++)
        StrCpyAsm(to, from);
    dur = usec() - start;
    printf("Asm took %lu microseconds\n", dur);
    }
"You can't actually make computers run faster, you can only make them do less." - RiderOfGiraffes

jahboater
Posts: 4598
Joined: Wed Feb 04, 2015 6:38 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 2:38 am

Michiel O. wrote:
Tue Jul 23, 2019 2:06 am

• The version above still does a C calling frame setup and teardown, I think that can be substituted for a simple register push and pop. That probably requires StrCpyAsm in its own pure assembly file, strcpyasm.s, and compiling/linking it in.
Just inline it if the compiler has not already done so.
The "inline" keyword is just a hint, you can force functions to be inlined with

#define inline __inline__ __attribute__ ((always_inline))

Then you can write (with a few other tweaks):-

Code: Select all

static inline char *
StrCpyMichiel( char *dst, const char *src ) {
    char * const d = dst;
    while( (*dst++ = *src++) != '\0' )
       ;
    return d;
}
Have you compared your functions against strcpy() itself?
See:-

Code: Select all

       -foptimize-strlen
           Optimize various standard C string functions (e.g. "strlen", "strchr" or "strcpy") and
           their "_FORTIFY_SOURCE" counterparts into faster alternatives.

           Enabled at levels -O2, -O3.
Use a modern version of GCC (8.3 on the latest Raspbian Buster is OK) and look at the assembler produced with

-S -fverbose-asm

By the way, "while( (*dst++ = *src++) != '\0' )" is preferable to avoid warnings from the compiler (it will likely assume that you have forgotten the second =), and will of course produce identical code. GCC says this:

Code: Select all

try.c: In function 'StrCpyMichiel':
try.c:12:9: error: suggest parentheses around assignment used as truth value [-Werror=parentheses]
   12 |  while (*dst++ = *src++);
      |         ^
Finally, for your assembler function, what compiler are you using? How do you know that src and dst are in R0 and R1?
They may be because of the ABI, but if the compiler chose to inline you function, they may well not be. And you have not told the compiler that R0, R1, and R2 are modified (called "clobbered").

This code will work with popular compilers.
It has one less instruction in the loop, allows the compiler to optimize the call into the surrounding code, and correctly informs the compiler that R0 and memory are altered as well as the two arguments.

Code: Select all

static inline void 
StrCpyAsm( char *dst, const char *src )
{
  asm( "1: ldrb r0,[%1],1; strb r0,[%0],1; cbnz r0,1b" 
       : "+r" (dst), "+r" (src) :: "r0", "memory" );
}
Last edited by jahboater on Tue Jul 23, 2019 3:10 am, edited 3 times in total.

Heater
Posts: 13082
Joined: Tue Jul 17, 2012 3:02 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 3:01 am

Michiel O.
My suggestion is to use pointers for strcpy:
Not only is this more in the spirit of C, but it's also quite a lot more efficient:
No it is not.

OK. Some comments on the actual code.

1) Who in their right mind would write a string copy function in C like that when there is one in the standard library of every C compiler

2) Turns out that DavidS' use of arrays is faster than Michiel O. use of pointers. See below.

3) I can't comment on the assembler version but given the massive lead of C's strcpy on various platforms it seems pointless to use assembler for this.

4) In general we should not be using strcpy in 2019. For all kind of reasons that everyone should be aware of my now.

On my Pi 3 running Buster:

Code: Select all

$ cat strcpyX.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <string.h>

char *StrCpyDavid(char *s, char *t){
    for(int cnt = 0; (s[cnt] = t[cnt]); cnt++);
    return s;
    }

char *StrCpyMichiel(char *dst, char *src) {
    char *d = dst;
    while (*dst++ = *src++);
    return d;
    }

// Get current time in microseconds
unsigned long usec(){
    struct timeval currentTime;
    gettimeofday(&currentTime, NULL);
    return currentTime.tv_sec * (int)1e6 + currentTime.tv_usec;
    }

int main(void) {
    char from[] = "Hello, world! How are you? I'm find, thanks! This is just a test string.";
    char to[80];

    unsigned long start = usec();
    for (int i=0; i<10000; i++)
        StrCpyDavid(to, from);
    unsigned long dur = usec() - start;
    printf("David took %lu microseconds\n", dur);

    start = usec();
    for (int i=0; i<10000; i++)
        StrCpyMichiel(to, from);
    dur = usec() - start;
    printf("Michiel took %lu microseconds\n", dur);

    start = usec();
    for (int i=0; i<10000; i++)
        strcpy(to, from);
    dur = usec() - start;
    printf("string.h took %lu microseconds\n", dur);
    }

$ gcc -Wall -O3 -o strcpyX strcpyX.c
strcpyX.c: In function ‘StrCpyMichiel’:
strcpyX.c:13:12: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
     while (*dst++ = *src++);
            ^

$ ./strcpyX
David took 1845 microseconds
Michiel took 1987 microseconds
string.h took 750 microseconds
On a Pi 3 running the 64 bit Pi 64

Code: Select all

$ uname -a
Linux pi64-aalto 4.11.12-pi64+ #1 SMP PREEMPT Sun Jul 30 20:18:20 CEST 2017 aarch64 GNU/Linux
pi@pi64-aalto:~$ gcc -Wall -O3 -o strcpyX strcpyX.c
strcpyX.c: In function 'StrCpyMichiel':
strcpyX.c:13:5: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
     while (*dst++ = *src++);
     ^~~~~
pi@pi64-aalto:~$ ./strcpyX 
David took 1997 microseconds
Michiel took 2032 microseconds
string.h took 59 microseconds
On an Intel x86 PC:

Code: Select all

$ uname -a
Linux monster 4.4.0-17134-Microsoft #706-Microsoft Mon Apr 01 18:13:00 PST 2019 x86_64 GNU/Linux
$ gcc -Wall -O3 -o strcpyX strcpyX.c
strcpyX.c: In function ‘StrCpyMichiel’:
strcpyX.c:13:12: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
     while (*dst++ = *src++);
            ^
$ ./strcpyX
David took 578 microseconds
Michiel took 583 microseconds
string.h took 19 microseconds

jahboater
Posts: 4598
Joined: Wed Feb 04, 2015 6:38 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 3:17 am

Heater,

For obvious reasons the strcpy() call in the test code is simply being converted to memcpy() by the compiler.

Your point is well made though.

I wish people would look at the assembler produced by the compiler.

The code produced for the two hand written C functions is the same (GCC 9.1 -Os ), so the choice of array indexes or pointers is moot.

StrCpyDavid

Code: Select all

 140                .L7:
 141                @ try.c:7:  for(int cnt = 0; (s[cnt] = t[cnt]); cnt++);
 142 002c 0100D1E4      ldrb    r0, [r1], #1    @ zero_extendqisi2  @ _40, MEM[base: _64, offset: 0B
 143                @ try.c:7:  for(int cnt = 0; (s[cnt] = t[cnt]); cnt++);
 144 0030 000050E3      cmp r0, #0  @ _40,
 145                @ try.c:7:  for(int cnt = 0; (s[cnt] = t[cnt]); cnt++);
 146 0034 0100C2E4      strb    r0, [r2], #1    @ _40, MEM[base: _65, offset: 0B]
 147                @ try.c:7:  for(int cnt = 0; (s[cnt] = t[cnt]); cnt++);
 148 0038 FBFFFF1A      bne .L7     @,
StrCpyMichiel

Code: Select all

 165                .L9:
 166                @ try.c:13:     while ((*dst++ = *src++) != 0 );
 167 0068 0120D0E4      ldrb    r2, [r0], #1    @ zero_extendqisi2  @ _45, MEM[base: src_42, offset:
 168                @ try.c:13:     while ((*dst++ = *src++) != 0 );
 169 006c 000052E3      cmp r2, #0  @ _45,
 170                @ try.c:13:     while ((*dst++ = *src++) != 0 );
 171 0070 0120C1E4      strb    r2, [r1], #1    @ _45, MEM[base: _4, offset: 0B]
 172                @ try.c:13:     while ((*dst++ = *src++) != 0 );
 173 0074 FBFFFF1A      bne .L9     @,
The assembler function is so dangerously wrong that I don't dare run it :(

Heater
Posts: 13082
Joined: Tue Jul 17, 2012 3:02 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 3:40 am

jahboat,
For obvious reasons the strcpy() call in the test code is simply being converted to memcpy() by the compiler.
Good point.

Moving the source string out of main seems to fix that. But still the standard strcpy is many times faster than those presented here.

jahboater
Posts: 4598
Joined: Wed Feb 04, 2015 6:38 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 3:47 am

I was amused that "while (*dst++ = *src++)" and "for(int cnt = 0; (s[cnt] = t[cnt]); cnt++)" emit the same code.

It just shows how this sort of micro optimization is pointless nowadays.
Just choose the simplest and most readable version.

Heater
Posts: 13082
Joined: Tue Jul 17, 2012 3:02 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 4:11 am

Exactly.

Are we now "spitting" on someone's code?

I was thinking about that...

I thing "spitting" is a rather overly strong way to describe constructive criticism but of course one does not have to program for very long before one finds that a favorite pass time of programmers is to pour ridicule on other programmers code. They will say your formatting is wrong, your structure is wrong, your choice of variable names is wrong, you should have done it this other faster way, etc, etc oh, and by the way you are using the wrong language anyway and you suck.

Well, that can be annoying but it's OK, within reason, because:

1) If they are actually knowledgeable, skilled and experienced programmers there may well be something to learn from their ridicule. Your code may end up better for having bugs pointed out. That's what code reviews are for.

2) Meh, so they don't like my formatting, variable names etc. Who cares. Grow a think skin, listen to their opinions, ignore it :)

BUT, there are two area's where people will shout their differing opinions and for sure many of them are provably wrong. That of course is correctness and performance.

The way to ensure you don't suck and are on the right side of the fence there is simple. Just test and measure your suggestion properly before shouting.

User avatar
Michiel O.
Posts: 178
Joined: Mon Dec 12, 2016 12:06 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 5:01 am

It's incredible what difference -O3 makes. And thanks for showing how to write better inline asm!
"You can't actually make computers run faster, you can only make them do less." - RiderOfGiraffes

ejolson
Posts: 3402
Joined: Tue Mar 18, 2014 11:47 am

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 6:14 am

Heater wrote:
Tue Jul 23, 2019 3:01 am
1) Who in their right mind would write a string copy function in C like that when there is one in the standard library of every C compiler
Reasons to write the strcpy by hand might be
  • To see how much faster the library version is?
  • To see how good the C optimiser is?
  • To document in a high-level language what strcpy semantically means?
  • To create a portable implementation independent of a library?
  • To use as a point of reference for Duff's device?
  • To amuse people in this forum?
Feel free to add to this list as appropriate.

jahboater
Posts: 4598
Joined: Wed Feb 04, 2015 6:38 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 6:19 am

ejolson wrote:
Tue Jul 23, 2019 6:14 am
Heater wrote:
Tue Jul 23, 2019 3:01 am
1) Who in their right mind would write a string copy function in C like that when there is one in the standard library of every C compiler
Reasons to write the strcpy by hand might be
  • To see how much faster the library version is?
  • To see how good the C optimiser is?
  • To document in a high-level language what strcpy semantically means?
  • To create a portable implementation independent of a library?
  • To use as a point of reference for Duff's device?
  • To amuse people in this forum?
Feel free to add to this list as appropriate.
strcpy() returns the value of the first argument, the destination.
Its much more useful, and the code is simpler, to return the final position of the dst pointer, so you can chain strcpy()'s together.

User avatar
Michiel O.
Posts: 178
Joined: Mon Dec 12, 2016 12:06 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 6:24 am

jahboater wrote: Its much more useful, and the code is simpler, to return the final position of the dst pointer, so you can chain strcpy()'s together.
That sounds a lot more efficient than a strcat() feast.
"You can't actually make computers run faster, you can only make them do less." - RiderOfGiraffes

ejolson
Posts: 3402
Joined: Tue Mar 18, 2014 11:47 am

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 6:29 am

jahboater wrote:
Tue Jul 23, 2019 6:19 am
ejolson wrote:
Tue Jul 23, 2019 6:14 am
Heater wrote:
Tue Jul 23, 2019 3:01 am
1) Who in their right mind would write a string copy function in C like that when there is one in the standard library of every C compiler
Reasons to write the strcpy by hand might be
  • To see how much faster the library version is?
  • To see how good the C optimiser is?
  • To document in a high-level language what strcpy semantically means?
  • To create a portable implementation independent of a library?
  • To use as a point of reference for Duff's device?
  • To amuse people in this forum?
Feel free to add to this list as appropriate.
strcpy() returns the value of the first argument, the destination.
Its much more useful, and the code is simpler, to return the final position of the dst pointer, so you can chain strcpy()'s together.
I like that--maybe even done so. If allowed, it's also possible to use sprintf to paste strings together. I wonder how that compares for speed?

Heater
Posts: 13082
Joined: Tue Jul 17, 2012 3:02 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 6:38 am

ejolson,
To document in a high-level language what strcpy semantically means?
Hmm... let me have a go at that. Something like:

Code: Select all

char *strcpy(char *dest, const char *src)
{
    for (int i = 0 ; i < rand() ; i++ ) {
      *dest++ = (char)rand();
   }
   return dest;
}
No seriously. Whichever way I read the C language standard the only way I can interpret strcpy() is as "undefined behavior".

It's not even possible to write a function in a high level language that does what C's strcpy does. Well, except C++ of course :)

jahboater
Posts: 4598
Joined: Wed Feb 04, 2015 6:38 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 6:43 am

ejolson wrote:
Tue Jul 23, 2019 6:29 am
strcpy() returns the value of the first argument, the destination.
Its much more useful, and the code is simpler, to return the final position of the dst pointer, so you can chain strcpy()'s together.
I like that--maybe even done so. If allowed, it's also possible to use sprintf to paste strings together. I wonder how that compares for speed?
[/quote]I think anything like that stpcpy(), strcat() etc are much much faster than using sprintf, probably orders of magnitude faster. Printf has to parse the format string first.

As for returning the end position, for the typical strcpy() code "while (*dst++ = *src++)", its just a case of returning "dst - 1" so that it returns a pointer to the terminating NUL. Its what stpcpy() does but that's not in the C standard (though it is POSIX).

jahboater
Posts: 4598
Joined: Wed Feb 04, 2015 6:38 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 6:46 am

Michiel O. wrote:
Tue Jul 23, 2019 5:01 am
It's incredible what difference -O3 makes.
Yes indeed.

A tip to look at the code produced by the compiler, with the C source code included (so its very easy to find stuff):
Use the latest Raspbian (Buster) which has a decent version of GCC (8.3).

Code: Select all

gcc -O3 -S -fverbose-asm hello.c -o hello.s
then just look at hello.s

Heater
Posts: 13082
Joined: Tue Jul 17, 2012 3:02 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 6:54 am

That's a great idea.

Returning the end position of the dest string will allow chaining of string copies, printfs and so on, and enable people to create buffer over run security vulnerabilities even faster than they can now.

User avatar
Gavinmc42
Posts: 3617
Joined: Wed Aug 28, 2013 3:31 am

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 6:58 am

I've started exploring OpenGL and even WebGL on the Pi4.
They should be teaching JS.

Lots of science data visualisation and even WebGL gaming can now be done on Pi4s.
Who needs that old Perl and Python now?
Can throw away those C compilers too.
I'm dancing on Rainbows.
Raspberries are not Apples or Oranges

Heater
Posts: 13082
Joined: Tue Jul 17, 2012 3:02 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 7:11 am

Gavinmc42.

If you have webgl working on a Pi 4 nicely could you do me a little favor:

Have a look at my beginnings of a new webgl project here: https://otaniemi.conveqs.fi:3000/public/jatkasaari.html

You should be able to click and drag a view around the 3D scene and zoom with the scroll wheel. 3D map pins should appear when you click on the map.

Does it work at all? What kind of frame rate do you get?
They should be teaching JS.
Yes indeed. A far superior language. Importantly with a proper standard as well.
Who needs that old Perl and Python now?
Nobody.
Can throw away those C compilers too.
I say, steady on old chap. We need those to build the Javascript engines from.

jahboater
Posts: 4598
Joined: Wed Feb 04, 2015 6:38 pm

Re: I dont get it... Why is everyone from science schools so obsessed with Perl and Python when we got C?

Tue Jul 23, 2019 7:23 am

Michiel O,

Its good to see someone taking an interest in writing efficient code.

There is a saying "Look after the pennies, and the pounds look after themselves".

I guess if you care about the performance of small functions like strcpy() then you will be unlikely to write the sort of bloated slow code that's too common nowadays. For example, web browsers that take 100MB to open a new tab :(

Return to “C/C++”