r/badcode • • Apr 11 '21

python Polyglot

Post image
1.2k Upvotes

116 comments sorted by

492

u/pandolf86 Apr 11 '21

Wait is that compiling C at python runtime?

218

u/coopercm Apr 11 '21

Yes

0

u/[deleted] Apr 11 '21

[deleted]

180

u/mfb- Apr 11 '21

It only compiles the code if there is no compiled version yet! Or... any other file of the same name.

Otherwise it "only" checks if there is a file, and calls it.

182

u/[deleted] Apr 11 '21

And they chose the perfect name, a.out.

There's no way there's gonna be another a.out in there by chance.

71

u/KINGodfather Apr 11 '21

Do you mean there's...

no way a.out?

8

u/Flawlesscode Apr 12 '21

ive upvoted you, you have been downvoted in gods eyes

50

u/pkarlmann Apr 11 '21 edited Apr 11 '21

I don't know how python is doing this, but from your post it sounds like some form of "cache" in the form of a file. So:

  1. Open the file from disk. That already is a syscall, which means a CPU ring switch.

  2. Wait till the disks read head is in place.

  3. Read it into memory.

  4. And finally execute it.

  5. For "performance".

  6. ? (Profit?)

42

u/CoderCharmander Apr 11 '21 edited Apr 11 '21

/tmp is usually stored in the RAM on modern systems (that does not remove the performance hit of ring switching multiple times, though)

Edit: Oh, he compiles the program outside /tmp and then moves it there. Nevermind.

13

u/mfb- Apr 11 '21

Well, it's deliberately written to be bad code and not used anywhere... but presumably the compiling would be a very rare occurrence.

5

u/pkarlmann Apr 12 '21

Compiling is relatively fast as it happens in userspace and then is just written to an output. What really is the problem is the CPU ring switch. That means the CPU has to actually reset its own state, write its own state somewhere else in order to be able to restore it, then execute whatever privileged - kernel code - wants it to do and then restore the previous state. And that happens with every syscall - like open(). That wastes easily a couple of thousands of CPU cycles, whereas a simple CPU Firmware modulo would've been cheaper even with an interpreter.

6

u/TerrorBite Apr 12 '21

But also, you're not just jumping to a C subroutine and returning. You're executing a program which must allocate memory, go through all the process of starting up the C runtime, then execute the code, then exit back through the C runtime, and then your Python program needs to handle the return value and other output. There are a LOT of syscalls involved there.

The correct way to get performance-critical C code into Python is to compile it into a library using the Python.h header (producing a DLL on windows, my_c_lib.pyd; or a shared object on Linux, my_c_lib.pyo) and then in Python, you just import my_c_lib like it's a normal module.

4

u/britreddit Apr 12 '21

Wait, so couldn't you swap that file out for any arbitrary C binary and run whatever you wanted whenever that python function is called?

2

u/mfb- Apr 13 '21

You can, sure.

2

u/Teln0 Apr 11 '21

Now the best thing to do is to run this program as root, just to stay perfectly safe and secure

10

u/[deleted] Apr 11 '21

Hey, this IS python we’re talking about here

issa joke don’t hurt me

0

u/joelhowell Apr 11 '21

Aka, big brain

117

u/Klausaufsendung Apr 11 '21

This is sooo ridiculous. Why not use a web service instead? https://isevenapi.xyz/

52

u/LoquaciousRaven Apr 11 '21

Best thing about it are the ads:

{
  "ad": "Scarecrow wanted for field in Saskatchewan. Must not be afraid of birds. Email [email protected]", 
  "iseven": true
}

-15

u/AutoModerator Apr 11 '21

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/LoquaciousRaven, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

29

u/ads1419 Apr 11 '21

That's the best thing I've seen in days! Thanks for the laugh!

21

u/das_Keks Apr 11 '21

That's great! I wonder if they also use a sophisticated algorithm in the backend, to determine if a number is even or not.

23

u/fshpsmgc Apr 11 '21

I'd use machine learning, tbh It's a modern web service, they'd be dumb not to

11

u/Gezzoto Apr 11 '21

Exactly. It's fairly easy to generate training data for this problem.

4

u/Bootezz Apr 11 '21

I cant use it until it utilizes blockchain technology. That's a hard requirement for my project.

4

u/FloezeTv Apr 11 '21

They obviously just call their API /s

3

u/das_Keks Apr 11 '21

Yeah, you're right. Why bother to implement a complex algorithm, if they already have the API which does exactly that.

12

u/thatannoyingguy42 Apr 11 '21

Reminds me of the isEven and isOdd python libraries, where isEven depends on the isOdd library.

3

u/Taksin77 Apr 11 '21

That was in npm

1

u/thatannoyingguy42 Apr 11 '21

It also exists in npm? Wow, that's funny/sad. I found it a long time ago on pypi.

1

u/Taksin77 Apr 12 '21

Pretty sure the pypi version is just a meme.

1

u/ElG0dFather Apr 11 '21

They should offer "isOdd" functions calls for the same price! I shouldn't have to subscribe to another API for that!

0

u/Gezzoto Apr 11 '21

That is hilarious

0

u/da_martian Apr 11 '21

Damn I read that as i7api

242

u/[deleted] Apr 11 '21

“I think it is a CPU bug” 🤡

68

u/TheBrainStone Apr 11 '21

I love that assuming it’s real they didn’t notice that it only happened for negative numbers. Or in their case only -1. Like that they never bothered to even try an even negative number during debugging is such an entertaining thought.

And let’s not even talk about the inefficient implementation, that’s inspired by actual common practice. I m in love with this post

235

u/Square789 int mystery=*((int*)rand()) Apr 11 '21

in C, -1 % 16 is -1; thus the return value for is_even would be in front of the lookup array and undefinedTM.

Also a polyglot is source code that is valid in different programming languages, this is more of a... very enthusiastic jit compiler?

139

u/deprilula28 Apr 11 '21

my man is jit compiling c, ahead of his time

15

u/Scryser Apr 11 '21

Now we can only hope OP is a ABSolute mad man...

71

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 11 '21

Image Transcription: Code


def isEven__fast__(x):
    # this is a performance critical operation
    # so we are going to drop down to C
    c_code = """
    #include <stdlib.h>
    int is_even(int x) {
      // since this is performance critical
      // we are going to keep a table of commonly
      // used values and try to reduce into that case
      int ix = x % 16;
      const int lookup[16] = {
          1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1
      };
      return lookup[ix];
    }
    int main(int argc, char **argv) {
      return is_even(atoi(argv[1]));
    }
    """
    import subprocess, os # we only need these imports for this function
    
    # only compile if we don't have the binary yet.
    # otherwise it's cached
    if not os.path.exists('tmp/a.out');
        with open('/tmp/even.c', 'w') as f:
            f.write(c_code)
        # i know this works because i ported from bash
        # and it works in the terminal
        # also for performance, move it into /tmp so that the binary stays in me
mory
        subprocess.run('''
            cc -0fast /tmp/even.c
            mv a.out /tmp
        ''', shell=True)
    # ok now run it
    subprocessCompletedProcess = subprocess.run(['/tmp/a.out', str(x)])
    return_code = subprocessCompletedProcess.returncode
    print(return_code)
    if return_code == 0: # translate c boolean to python
        return False
    # originally i had checked for return code of 1 first
    # and then did catch-all to return True
    # but then sometimes to seemed the return code was 139 or 255 --
    # but only on certain CPUs. i think it is a CPU bug.
    # i didn't have time to track it down and it doesn't happen very
    # often so it's not crucial to the performance
    # so just put this in the catch all case
    #elif return_code == 1:
    else:
        #print(return_code)
        return True

if __name__ == '__main__':
    print(isEven__fast__(-1))
    print(isEven__fast__(0))
    print(isEven__fast__(1))
    print(isEven__fast__(2))
    print(isEven__fast__(15))
    print(isEven__fast__(1.5))

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

15

u/Little-Helper Apr 11 '21

Great work

138

u/[deleted] Apr 11 '21 edited Apr 11 '21

100% is satire

Love that this will execute any arbitrary a.out as well hahaha

17

u/[deleted] Apr 11 '21 edited Apr 11 '21

If only they stored the hash of the compiled code and compared it before running it... I think I would have to get a picture of it framed, satire or not!

Edit: Or, even better—verified the code by comparing its disassembly lol... I think I may wanna try something like this in like Kotlin or Java hahaha

50

u/starryhound Apr 11 '21

"Performance"

58

u/_PM_ME_PANGOLINS_ Apr 11 '21

They know that’s the performance critical part because they measured and it takes up 95% of the run time.

70

u/crixx93 Apr 11 '21

I feel sick after reading this

4

u/K1ngjulien_ Apr 11 '21

i'm angry now.

67

u/Beach-Devil i++++; Apr 11 '21

The comments just make it so much worse

45

u/vulpxn Apr 11 '21

hoo lee sheet

40

u/Ranvier01 Apr 11 '21

What. The fuck.

35

u/private_static_int Apr 11 '21

In what universe would this be faster than "return x%2==0"?

26

u/the_captain_cat Apr 11 '21

Even in the C code, x%16 with the 16 element array is fucking stupid.

5

u/[deleted] Apr 11 '21

Personally, I don't like relying on the optimizer for simple stuff so I still type (n&1)==0

1

u/Loewi_CW Apr 12 '21

Does that work in Python?

9

u/Vulcalien Apr 11 '21

I agree. I prefer THIS implementation, actually.

21

u/meneo Apr 11 '21

Jokes on him, he should have used the is even api

8

u/[deleted] Apr 11 '21

Exactly.

For real though, it would be faster. First of all, the overhead of compilation in itself is too big. Second, if using Windows, it would be slow since it would create a new thread, which is generally slow on windows. Third, on a mechanical drive, reading and writing speed is much slower than sending a request.

0

u/DZekor Apr 11 '21 edited Apr 12 '21

Wait is that compiling C at python runtime?

Compile it to ram for more speed ez. What could go wrong...
edit: to be clear that was a joke

17

u/PsCustomObject Apr 11 '21

Maybe I have a fetichism for comments but ‘ok now run it’ is what really got me :-)

17

u/akwaryos Apr 11 '21

That's what I call interpreted cython

22

u/LVNmaster Apr 11 '21

How do these people have a job? Like, every single idea here is so atrocious it hurts.

22

u/Mastergrow depraved Apr 11 '21

this is very obviously a joke

5

u/[deleted] Apr 11 '21

[removed] — view removed comment

9

u/CheezyArmpit Apr 11 '21

Writing long inefficient isEven programs is a meme, so many people wooshed here.

4

u/[deleted] Apr 11 '21

They must have never heard of the Python c api

Or maybe they thought that's how a JIT works

7

u/sneakykenny Apr 11 '21

+ you can actually give the code as stdin to gcc and give it a flag to set the output file path, making this even worse than it already is 🤔

11

u/taptrappapalapa Apr 11 '21

Hopefully this wasnt in any sort of production code. I can just imagine the security issues that this would cause.

21

u/life_npc Apr 11 '21

an isEven function? this boy is clearly memeing

17

u/meneo Apr 11 '21

Clearly, is even has become a meme since the iseven npm package incident

9

u/hoss_pumpkin Apr 11 '21

anyone know the theme?

13

u/TheEnderChipmunk Apr 11 '21

I think it's solarized light? Nor sure

0

u/hoss_pumpkin Apr 11 '21

i was thinking that’s what it was but for some reason remembered solarized light being a bit brighter

1

u/db2 Apr 11 '21

Yakety Sax?

7

u/MyChaOS87 Apr 11 '21

What's so hard with (x & 1)

9

u/ShatterdPrism Apr 11 '21

Remind me if I am wrong, but this is a bit wise Operator and it checks in this case if the last bit of x is a 1 which would mean the number isnt even, right?

6

u/MyChaOS87 Apr 11 '21

Yes, it's basically x%2

3

u/CodeLobe Apr 11 '21

!(x&1) // true if even (not odd), false otherwise.

In low level langs the ! /* not operator */ can be optimized away by using jump if zero JZ instead of JNZ, jump if not zero, or vise versa.

1

u/aeropl3b Apr 11 '21

Even in Python this should be faster than trying to compile a C kernel on the fly and then calling it via subprocess... subprocess alone is probably more expensive than most trivial operations...

1

u/ShatterdPrism Apr 12 '21

I find those kind of thought processes, optimization and low level abstraction very interesting to read.

But tbh I don't think it's something I could focus on for longer xD

10

u/[deleted] Apr 11 '21

Hey, ignoring the rest of the clusterfuck, it's pretty cool you can compile and run shell commands from python

Edit: shell

13

u/Shakespeare-Bot Apr 11 '21

Ho, ignoring the rest of the clusterfuck, t's quaint merit thee can compile and runneth the lady'll hests from python


I am a bot and I swapp'd some of thy words with Shakespeare words.

Commands: !ShakespeareInsult, !fordo, !optout

5

u/recycle4science Apr 11 '21

This is a terrible bot, it's 'tis and thou. And it has the clbuttic error, which is extra rich on a programming sub.

6

u/jarfil Apr 11 '21 edited May 12 '21

CENSORED

0

u/[deleted] Apr 11 '21

Could be confused between the ‘t’ flag for directories and executables.

8

u/[deleted] Apr 11 '21

It’s bizarre to me that so many people don’t get that it’s a joke

5

u/[deleted] Apr 11 '21

This is what I call A Fast JIT Engine. Blows LLVM out of the water.

I also love how they didn't even bother to replace the number directly in the Python string, and they opted for command line arguments.

6

u/TheBrainStone Apr 11 '21

Using it as a command line parameter is actually faster as it only compiles once.
So I agree very disappointing.

0

u/[deleted] Apr 11 '21

You are correct, haven't thought about it.

1

u/joske79 Apr 11 '21

You should add caching. Once we looked up a value we can remember whether it's even, odd or something else. Maybe remember the last 10,000 values that were queried?

0

u/coopercm Apr 11 '21

Good idea.

4

u/oshawa_connection Apr 11 '21

Surely this is satire? It's an isEven function

3

u/pkarlmann Apr 11 '21

How much I hate this "we" crap.

3

u/[deleted] Apr 11 '21

3

u/RecDep Apr 11 '21 edited Apr 11 '21

Why not send the C code into the compiler through stdin?? Why not use -o to write the output directly to the desired file path?? Why not compile in advance and use Python’s builtin support for C?????

I hate everything about this post, it just gets worse the more you read into it.

5

u/zexen_PRO Apr 11 '21

Pretty sure it’s a joke. God, I hope it’s a joke. Please let it be a joke.

2

u/intangibleTangelo Apr 11 '21

pff. should have built a library and called it with ctypes.

2

u/[deleted] Apr 11 '21

Or you could just look at the last bit?

1

u/acid_minnelli Apr 11 '21

Ok but this isnt the w o r s t idea.

I would move the c code in to its own file, it doesn't need to be hard coded in to this file.

Also the code to check whether compilation has happened before needs work on.

But the idea of running C code from Python is a great idea (its how the scientific packages work) & who ever wrote this is clearly thinking in the right direction.

1

u/ikoniq93 Apr 13 '21

Just to make sure I'm reading this clusterfuck right...

We're using JIT compilation of C code to find if a number is even or odd, then handing that off to the rest of the script as a boolean to continue to run?

Wouldn't it be easier to just do the number mod 2 and then use an if statement to return false if the result isn't zero?

tbf i'm not super familiar with python but that just seems to be the logical answer to me.

1

u/oderjunks Apr 14 '21

aaaaaaaaaAAAAAAAAAAAAAAAA

1

u/Rudxain let let.let = 'let' Apr 16 '21

Is x % 16 really faster than x % 2 ?

1

u/carcigenicate Apr 11 '21

Obviously a joke, but funny.

1

u/Socialimbad1991 Apr 11 '21

Good to see they've covered 16 of the most common cases here

1

u/[deleted] Apr 11 '21

O M G! There is a fine line between clever and stupid, but this code never gets close to that line.

0

u/FireCrack Apr 11 '21

This must be an elaborate troll

0

u/Iseefloatingstufftoo Apr 11 '21

So they just wrote Numba from scratch? Haha.

0

u/[deleted] Apr 11 '21

Oooooh, ILSpy :-)

0

u/DrCrossBones Apr 11 '21

What did I just see

0

u/snotfart Apr 11 '21 edited Jul 01 '23

I have moved to Kbin. Bye. -- mass edited with redact.dev

0

u/[deleted] Apr 11 '21

I mean, that's kinda how we write OpenCL code. And nobody has a problem with that.

0

u/Pangocciolo Apr 11 '21

Performance critical. Path exists. Convert x to string. Sure.

0

u/CarterNotSteve Apr 11 '21

What ide/editor?

0

u/yard2010 Apr 11 '21

He is using python as I used PHP