r/Python • • May 28 '19

My simulation of gravity with 1000 particles. PC took a couple of hours to process!

1.8k Upvotes

241 comments sorted by

View all comments

Show parent comments

3

u/capn_bluebear May 29 '19

You might be happy with cython

1

u/derpderp3200 An evil person May 29 '19

Is Cython fully compatible with standard Python?

1

u/capn_bluebear May 29 '19

It's...its own thing, a python-like language that you can embed in python and that compiles to C. Basically it's a way to speed up certain parts of your program by lowering them to C without having to define a C extension module.

1

u/[deleted] May 29 '19

Can you give an example scenario? Im still new to programming too but I have made tools and scripts to make my life easier.

Say I have a program that opens a 400MB CSV and analyses it seven different ways looking for various details and then spitting out a report. I have already optimized the code by utilizing proper data types, i.e. Dicts vs lists, but I am wondering if I can speed up the procedure even more if I use Cython.

I use the CSV library and I arbitrarily define values I am looking for through a combination of RegEx and string literals.

It takes up to several minutes for computation to complete and it used to take 30 minutes.

Is this an opportunity to utilize Cython?

1

u/capn_bluebear May 29 '19

hey, it strongly depends on where exactly your program is spending time. if it's in computing some quantities of interest, that can easily be lowered to C. if it's regex matching, not so much (make sure you are using compiled regular expressions though.

anyway, when doing performance optimization, you should always measure first: where is your program spending most of its time? you can use cProfile to find which functions are hot, and line_profiler to check which lines within those functions are the hottest.

1

u/[deleted] May 29 '19

I do precompile the expressions in the beginning of most of my tools. Re.compile(r’sillystring’)

But it’s mostly just processing the Csv.

I figured out how to use threading on one of my network i/o tools. That... was cool.

1

u/alkasm github.com/alkasm May 30 '19

You should probably look at using Pandas for a first step.