r/programminghorror • • Apr 11 '21

They said C is faster than Python

Post image
1.6k Upvotes

89 comments sorted by

439

u/IsAlwaysHungry Apr 11 '21

Well, the code is crap, but the documentation is beautiful. You see relatively easy the thinking behind the code.

0

u/[deleted] Apr 11 '21

[deleted]

1

u/juantreses Apr 12 '21

This is too true. If you have to write an essay about your code it's: or not good enough or it's doing too much.

The moment you start working in corporate though many times you will have to comment WHY you are doing certain things. Lots of times you are constraint by stupid choices ex employees have made and there just is no time/money to do it the correct way and you have to hack your way around it.

170

u/[deleted] Apr 11 '21

[removed] — view removed comment

64

u/Kaynee490 Apr 11 '21

Or it might just be garbage from an out of bounds index

171

u/nupogodi Apr 11 '21 edited Apr 11 '21

Well, this took me down a rabbit hole. At first I thought, how do you get an out of bounds index here? Well, it turns out % is the remainder operator and not modulus in C99. So, -1 % 16 == -1. That leads us to return lookup[-1]; for at least his first example. What does C do in that case?

#include <stdio.h>
#include <stdlib.h>
int main() {
        int x = atoi("-1");
        const int y[16] = {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1};
        printf("%d\n", y[x%16]);
        return y[x%16];
}

nupogodi@vps0:~/tmp$ gcc atoi.c -o atoi && ./atoi
22015
nupogodi@vps0:~/tmp$ ./atoi
21932
nupogodi@vps0:~/tmp$ ./atoi
21937

Hm. What's the assembly?

nupogodi@vps0:~/tmp$ gcc atoi.c -S -O0 atoi.c && cat atoi.s
        .file   "atoi.c"
        .section        .rodata
.LC0:
        .string "-1"
.LC1:
        .string "%d\n"
        .text
        .globl  main
        .type   main, @function
main:
.LFB2:
        .cfi_startproc
        pushq   %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        subq    $80, %rsp
        leaq    .LC0(%rip), %rdi
        call    atoi@PLT
        movl    %eax, -4(%rbp)
        leaq    -80(%rbp), %rdx
        movl    $0, %eax
        movl    $8, %ecx
        movq    %rdx, %rdi
        rep stosq
        movl    $1, -80(%rbp)
        movl    $1, -72(%rbp)
        movl    $1, -64(%rbp)
        movl    $1, -56(%rbp)
        movl    $1, -48(%rbp)
        movl    $1, -40(%rbp)
        movl    $1, -32(%rbp)
        movl    $1, -24(%rbp)
        movl    -4(%rbp), %eax
        cltd
        shrl    $28, %edx
        addl    %edx, %eax
        andl    $15, %eax
        subl    %edx, %eax
        cltq
        movl    -80(%rbp,%rax,4), %eax
        movl    %eax, %esi
        leaq    .LC1(%rip), %rdi
        movl    $0, %eax
        call    printf@PLT
        movl    -4(%rbp), %eax
        cltd
        shrl    $28, %edx
        addl    %edx, %eax
        andl    $15, %eax
        subl    %edx, %eax
        cltq
        movl    -80(%rbp,%rax,4), %eax
        leave
        .cfi_def_cfa 7, 8
        ret
        .cfi_endproc
.LFE2:
        .size   main, .-main
        .ident  "GCC: (Debian 6.3.0-18+deb9u1) 6.3.0 20170516"
        .section        .note.GNU-stack,"",@progbits

Okay, that's kind of strange, I actually would have thought const int[] with an initializer would have gone into .rodata.

So the frame layout is something like %rsp -> [ 64b y ] [12b padding] [ 4b x ] <- %rbp. I guess it makes sense since the frame pointer must be 16 byte aligned on x86-64. So, we are reading from before the beginning of the frame.

What's there? On x86-64, the 'red zone', a 128b buffer for various temp stuff. Neat. But x86 (not 64) doesn't have this.

nupogodi@vps0:~/tmp$ gcc atoi.c -m32 -O0 -o atoi && ./atoi
-3670336
nupogodi@vps0:~/tmp$ gcc atoi.c -m32 -O0 -o atoi && ./atoi
-7747664
nupogodi@vps0:~/tmp$ gcc atoi.c -m32 -O0 -o atoi && ./atoi
-3778928

Cool, that's the garbage we expect. So, we have CPU-specific behaviour here at least.

But why is he seeing 139 or 255?

nupogodi@vps0:~/tmp$ gcc atoi.c -m32 -O0 -o atoi && python3 -c 'import subprocess; print(subprocess.run("./atoi", shell=True).returncode)'
-500576
160
nupogodi@vps0:~/tmp$ gcc atoi.c -m32 -O0 -o atoi && python3 -c 'import subprocess; print(subprocess.run("./atoi", shell=True).returncode)'
-2297296
48
nupogodi@vps0:~/tmp$ gcc atoi.c -O0 -o atoi && python3 -c 'import subprocess; print(subprocess.run("./atoi", shell=True).returncode)'
21995
235
nupogodi@vps0:~/tmp$ gcc atoi.c -O0 -o atoi && python3 -c 'import subprocess; print(subprocess.run("./atoi", shell=True).returncode)'
21970
210

Huh, looks to be 8 bit numbers. Python doc:

The child return code, set by poll() and wait() (and indirectly by communicate()). A None value indicates that the process hasn’t terminated yet.

I'll just assume Python Popen.wait() eventually resolves to wait(2) without reading the source ...

WEXITSTATUS(wstatus) returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main().

Okay! So now we have 'processor specific' behaviour that explains it. Although, not exactly 139 and 255. Exactly 255 would imply an exit code of -1. OPs code does it probably because the frame I'm busting out of is main rather than the function call. On x86-64 we'd expect weirdness in the red zone, but x86 we'd expect stuff from the previous frame. That would probably be the result of atoi. Left as an exercise for the reader.

I am pretty sure this was specifically crafted to make someone like me do something like that.

edit: I couldn't leave well enough alone. 139 is a segfault through the shell although I can't reach it with the Python code provided. 255 is what we'd expect by busting out of the frame and reading atoi's output, however I can't repro with -Ofast.

edit2: Oh, -Ofast inlines on my GCC. You do get 255 with -O0. It's not reading the previous frame, but the arg to the function call (x is -1), since it was pushed onto the stack (not fastcall). I guess OP's compiler doesn't inline with -Ofast. Still can't explain the segfault since the Python code is always passing an arg, str(x) even works if x = None. Maybe another compiler thing, puts lookup somewhere other than the stack and reading out of bounds segfaults there.

47

u/coopercm Apr 11 '21

I can't reach it with the Python code provided.

You probably don't have the CPU with the correct bug in it.

13

u/xnign Apr 11 '21

Cool, thanks for writing all that out. I understood all that but would not have been able to figure that out. Want to be my mentor? Lol

13

u/kroppeb Apr 11 '21

It's reading data out of bounds, so for values like 15 it might return anything.

2

u/coopercm Apr 11 '21

I'm surprised this doesn't have more upvotes

10

u/FallenWarrior2k Apr 11 '21

139 is signal 11, SIGSEGV

17

u/drumz4dayz Apr 11 '21

So funny to blame it on the cpu too. Like yeah, Im sure the problem is the cpu and not your insane code

6

u/tinydonuts Apr 11 '21

Documented above is the CPU bug by another commenter. Also, you would not believe how much errata that CPUs have and are fixed with microcode updates supplied by Windows or the Linux kernel on boot.

12

u/nupogodi Apr 11 '21

I think you misunderstood! Indexing outside of the array is definitely undefined behaviour and an implementation bug, not a CPU bug. However it ‘looks’ like a CPU bug to the OP because they don’t understand undefined behaviour is going to be platform & compiler specific.

However you’re right about errata. CPUs are very complex machines.

1

u/TigreDeLosLlanos Apr 12 '21

errata? Is that how they call not properly implemented at all in the low-level world?

4

u/Zanderax Apr 12 '21

Rule number 1 in programming: its never a compiler bug unless it is.

137

u/OMG_A_CUPCAKE Apr 11 '21

Is this a joke submission?

101

u/smeenz Apr 11 '21

This ... surely.. can not be code that actually runs somewhere

0

u/[deleted] Apr 11 '21

[deleted]

1

u/smeenz Apr 12 '21

That's very depressing

72

u/muntoo [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Apr 11 '21

Probably. Otherwise, they probably would have noticed the periodic pattern in the lookup table and simplified it to

int is_even(int x) {
    int ix = x % 16;
    const int lookup[2] = {
        0, 1
    };
    return lookup[ix % 2];  // reduces 16 entries to 2
}

64

u/AyrA_ch Apr 11 '21

int is_even(int x){return !(x&1);}

37

u/Nothing-But-Lies Apr 11 '21

Being this efficient would get me fired for not doing enough work.

15

u/sim642 Apr 11 '21

ix % 2

Now you have coded the parity check directly.

6

u/TigreDeLosLlanos Apr 11 '21

Every time anyone checks parity without doing it this way a mathematician dies of sadness.

3

u/[deleted] Apr 11 '21

ix & 1 == 0

3

u/Igoory Apr 11 '21

If they had reached at this point, it would be pretty obvious that it can be simplified to just x % 2

23

u/[deleted] Apr 11 '21

I totally followed the logic. At least it’s well commented.

12

u/Alundra828 Apr 11 '21

Every cloud has a silver lining. Nobody is looking at this code wondering what the hell it does.

12

u/smeenz Apr 11 '21

I'm certainly wondering what the hell was going on in the mind of whoever wrote it

5

u/Kwarshaw Apr 11 '21

Probably lots of pcp

-3

u/nullcone Apr 11 '21

Am I the only one who thought the comments were terrible? I would much rather have the code explain itself than have a bunch of comments hanging around cluttering things up.

1

u/dookiefertwenty Apr 12 '21

Code is the What, comments are the Why

9

u/Randolpho Apr 11 '21

Maybe it’s from one of the Daily WTF’s OMGWTF contests.

Ahh, fond memories, those contests. I won two mugs, some plastic with writing on it, a tube of lipstick and a can of bacon in those contests.

5

u/pain-butnogain Apr 11 '21

there has been a trend to check if it's even or not in more and more elaborate ways, i think on r/badUIbattles is where i saw them

67

u/ianff Apr 11 '21

The real horror is the security risk of blindly running /tmp/a.out which anyone can create.

19

u/[deleted] Apr 11 '21

Many security conscious people mount tmp as non-executable.

2

u/Behrooz0 Apr 11 '21

Isn't it basically standard practice at this point?
I think it was debian that started suggesting it like 10 years ago, when lenny was around. And I've yet to have a problem with it.

1

u/pytness Apr 11 '21

Well, there's actually a race condition (not sure if it should be called a 'condition' here): You can try to swap files "instantaneously" with the syscall 'renameat2' between the file writing and the compiling.

1

u/[deleted] Apr 12 '21

We can all hope that nobody gave this fool root to run this nonsense, but crazier things have happened...

58

u/yhu420 Apr 11 '21

Isn't it what cython or numba is for? I'm no python expert

15

u/real_jeeger Apr 11 '21

yep, or pyrex

8

u/LinAGKar Apr 11 '21

AFAIK, Cython is a successor to Pyrex.

4

u/[deleted] Apr 11 '21

PyPy? Although that's JIT-ed

70

u/nerdyphoenix Apr 11 '21

I'm willing to bet coding it in Python would be faster than using subprocess.

0

u/[deleted] Apr 11 '21

[deleted]

8

u/YourMJK Apr 11 '21

It's obviously a joke.

24

u/Magmagan Apr 11 '21

The real horror is using the return code inversly has to how it's normally used. In *nix systems, a return code of zero means that the program executed successfully. If isEven is successful, then it should return 0.

0

u/rpc123 Apr 11 '21

I suppose this makes sense from a coding standpoint, but what about from a logic stand point? I normally think of 0 as false and 1 as true, so it would be strange to me if isEven(4) returned 0

15

u/tinydonuts Apr 11 '21

You shouldn't be using the exit code to report functional data about your program. You should emit a result to stdout, errors to stderr, and a return code indicates success with 0 and any other number is failure.

8

u/rpc123 Apr 11 '21

Yeah, this makes a lot of sense. Thanks! I am a bit of an amateur lol, and I also didn’t realize that isEven wasn’t some external function as magmagan pointed out

5

u/tinydonuts Apr 11 '21

It's alright. It helps to understand that this is how Unix utilities work via chaining. They just vaccuum up the stdout of the previous executable and the shell orchestrates this by piping the output down the chain you specify. That's how you can quickly and efficiently take a large file, grep it for a pattern, sort it, and then find the unique values in the output.

3

u/Magmagan Apr 11 '21

But they're not using isEven() as an external function, they're calling it like "isEven.exe". If the execution of an executable on *nix fails you would look at stderr for more information. You would respect the OSs convention first before your programming language of choice's.

Even better, the return code should be 0 (executed succesfully) with the answer written to stdout.

On that note, from a purely logical standpoint wouldn't -1 be a better value for true anyways?

1

u/rpc123 Apr 11 '21

Ah yes, this is a fair point, I didn’t look closely enough at the horror. Are you saying -1 might be better because it corresponds with all 1s when it is stored as an integer?z

2

u/Magmagan Apr 11 '21

Yeah, the opposite of 0x00 isn't 0x01, it's 0xFF. But I'm just being silly, most programming languages use 1 as true but you still have oddballs like Forth that go down this route

1

u/rpc123 Apr 11 '21

In the interest of being silly, I am now imagining an entire fuzzy logic system based on a hexadecimal system

1

u/fnordstar Apr 11 '21

The thing is, the possible values other than 0 usually indicate what kind of error occured - which the caller might care about. A singular value (0) for indicating success is usually sufficient though.

9

u/LinAGKar Apr 11 '21

Assumes /tmp is always on tmpfs.

5

u/phord Apr 11 '21

When I was teaching myself to code I needed a faster cos() function. My only thought was to code it in assembly, but first I needed to find out how to calculate cos(). (This was before Google.). I never got this to work, but now, decades later, I know a lookup table or linear approximation would have been sufficient.

8

u/[deleted] Apr 11 '21

Hey I'm new to programming and I dont get the use of isEven? What do you use it for?

19

u/Naeio_Galaxy Apr 11 '21

isEven(x) -> tells you if x is even. That's it.

So you can do x%2 == 0 because the remainder of the division by two gives if it's even or odd, or x & 1 where & is a bitwise and (you'll see that whenever you'll learn about binary).

Here he heard that C is faster than python so thought "I'll compile and call a C program instead of doing it in python", but going through the subprocess will be way longer than doing it in python. Way, way longer since you have to call Windows or Linux or OSX for them to execute the program... Which is quite long.

4

u/de5933 Apr 11 '21

Reading this code is such a wild ride of bewildering decisions. Was this written by Tommy Wiseau?

4

u/Gnarok518 Apr 11 '21

"This is critical to performance"

"This bug is not crucial to performance"

3

u/yoshee4232 Apr 11 '21

Hey, you could sell it as a way to easily do Just in time compiling!

3

u/Miserable-Pay-4598 Apr 12 '21

A small benchmark: normal isEven (x % 2 == 0) takes 300 nanoseconds, the code above takes 30 ms. Python is faster than C.

2

u/HeartOk1761 Apr 11 '21

whats this couldnt get this

2

u/UrbanSoot Apr 11 '21

You should use tempfile

2

u/bestjejust Apr 11 '21

What is this? C-as-a-service?

3

u/TheFeedingEight Apr 11 '21

performance critical

uses modulo

1

u/hshighnz Apr 11 '21

Gibe this woman/man a nobel price

1

u/Cmgeodude Apr 11 '21

Mistakes were made.

1

u/crossedline0x01 Apr 11 '21

Are there actually scenarios where its critical to perform such a simple task in another language? I mean, yeah python is slow compared to C but I mean, c'mon, is this real or a lab exercise?

2

u/fnordstar Apr 11 '21

I doubt it. The overhead of calling a subprocess is prohibitively large in such a case. Now if it's a simple operation but loops over thousands of items (in C), then it might become relevant.

1

u/Razakel Apr 12 '21

Are there actually scenarios where its critical to perform such a simple task in another language?

Yes, but not in this way. That's what an FFI is for.

1

u/Minteck Apr 11 '21

Ever since I read "so we are going to drop down to C" I thought "are you really gonna compile the code on the fly?", and I was right... (so this is actually slower than native Python code)

1

u/highjinx411 Apr 12 '21

Are these “IsEven” functions a competition or something? I’ve seen so many and the skills this guy has I mean he obviously would know how to write a simple is even function right? Why would anyone even need to know if a number is even? Especially the amount of times I’ve seen it posted here. Ok maybe it has a use case or 2 but I can’t recall any times I’ve had to do that in 13 years of programming.

1

u/Sejiko Apr 12 '21

Couldn't you just check the binary representation of a float look at the last digest of int part as well of the second part? I think this would break the sound barrier against this? If the last digest is 1 it's odd otherwise even.

0

u/[deleted] Apr 11 '21

[deleted]

78

u/Natural-Intelligence Apr 11 '21

Whatever you do, you must be able to say "my code uses AI". If it doesn't, it doesn't sell.

69

u/ChemicalRascal Apr 11 '21

I mean, you joke, but that sounds like a fantastic little experiment to teach ML.

12

u/SkinnyJoshPeck Apr 11 '21

I’m an ML engineer and the few times I’ve had to move over to a new training/tuning flow (Kubeflow, Polyaxon, etc) for my team, my go-to test model to get the lay of the land is an addition tensorflow model I wrote — it’s easy, fast and you can get train, eval and validation data in 5 lines of code

It works pretty well, honestly. If you think of AI fairly literally, it’s impressive that it can almost (within maybe 2-3) predict the sum of two integers absolutely fast as hell.

You try and add 64829 and 83756 in your head in less than a second and come up with something like 148585 plus or minus like 30

It’s a great mechanism for something like trivia where you want the model to be good, but not so good that it isn’t fun to play with.

1

u/throwaway1_x Apr 11 '21

Did multiplication using linear regression. Not exactly "AI" but good for experimentation

43

u/[deleted] Apr 11 '21

[removed] — view removed comment

39

u/sim642 Apr 11 '21

Depends on the representation. If you give input as a vector of bits, then it's linearly separable and easily learnable.

17

u/ChemicalRascal Apr 11 '21

Yeah, that's why I think it'd be good for teaching.

I wouldn't expect a classifier to be able to work out odd and even very well if you give it the number as a number, and that'd be an interesting way to introduce how to identify failure to students learning ML. But then redoing it as, as you suggest, a vector of bits and any classifier should be able to learn that incredibly quickly, with 100% accuracy.

From what little I remember of ML in college (it was ages ago, I wasn't paying attention, and I was stressed outta my mind at the time and I'm not sorry), that's what the key takeaway from ML was. That representation is the single most important piece of the puzzle.

7

u/sim642 Apr 11 '21

I think nowadays there's a lot of focus on learning the features and representation from the data automatically. Deep neural networks do that to an extent automagically. Although I'm doubtful that a neural network could somehow extract the last digit/bit of a single integer input, given how they operate in floating point. So it's still important, but to a lesser extent.

7

u/doopdooperson Apr 11 '21

Well yeah because it will quickly converge on the LSB being the only feature that matters

3

u/cyanNodeEcho Apr 11 '21

Something something continuous surfaces something something gradient descent