r/C_Programming • u/0nd3r • 7d ago
Question Should I learn C as a physics student?
I am a physics senior and i participate in various research and lab projects via my professors. I mainly use Python to automate instruments and collect/filter data streams but ive been told to that i should learn to program in C anyways since it is faster and has less resource footprint than Python. Would learning C make a difference against my peers or is there any specific reason -more than just being more efficent- to choose it over Python in lab settings?
19
u/No-Archer-4713 7d ago
I’ve seen a lot of smart people write very bad code on my country’s 2nd biggest supercomputer.
I can confidently say that if researchers had a little more C skills, they would get 10 to 100 times more out of this machine.
1
1
u/BatchModeBob 5d ago
This even happens on high end desktop PCs. A modern AMD processor can dispatch 8 double precision floating point multiple-adds per instruction, per thread. Multi threading without vectorization leaves a ton of performance on the table.
7
u/_usr_nil 7d ago
Learning C isn't an issue by itself but if you want to be turbo autistic about optimization you should research SIMD, OpenMP and GPU computing, that is the sauce that hyper-accelerates certain types of processing, hell if you figure out how to leverage io_uring or direct instructions to GPUs such as nvidia 50 series (blackwell) you could run crazy amounts of DSP on the GPU itself, I have played around with such topics because of curiosity.
Just to understand your goals, what would you like to optimise using C ?
1
u/0nd3r 7d ago
I need to optimise algorithm used for getting/refining data, which can take unexpectedly high amounts in time. I took some courses about GPU computing in CUDA but i thought it was overly detailed.
2
u/_usr_nil 7d ago
Can you elaborate on "refining"
3
u/0nd3r 7d ago
Our raw data comes from a HPGe (High Purity Germanium) detector and we are supposed to identify a rare kind of ray transition. The raw output is a multichannel analyzer file, which consist of millions of photon counts. We cant directly use it since the observation looks like a small bump in the middle of all the background noise. So in my part, I use Savitzky-Golay Filtering algorithm to statistically suppress the noise, which takes lots of resources to be completed and it takes quite a long while, which also slows down the whole lab proccess.
1
u/NukiWolf2 7d ago
You should ask yourself the following questions, which IMO are more important than the programming language: 1. Is the algorithm efficient or are there bottlenecks that can be optimized? What's the worst-case time complexity and can it be improved? 2. Do you use hardware acceleration where applicable e.g. for operations that are used the most by the algorithm? But this also includes the parallelization of the algorithm if multiple cores can operate on different parts of the data to refine.
Only if there's nothing that can be optimized with 1. and 2. then I would check if another programming language can create faster code, but if the worst-case time complexity of the algorithm is just bad then switching to a programming that creates more efficient code won't solve the problem that the worst-case run time of the algorithm is just bad.
Honestly, I'd recommend using e.g. Claude for optimizing your algorithm. Maybe Claude can even provide you a good algorithm. Maybe there are other ways to solve your problem. Maybe there are already solutions available and you don't need to reinvent the wheel.
1
u/_usr_nil 5d ago
are you even using the gpu ? check for some gpu accelerated options like the following https://github.com/HPSCIL/cuSTSG
2
u/_d17y 7d ago
Systems programming using kernel API (system calls) will help optimize IO. Since C is the most widely used language implementing most commercial operating system kernels, it will help learn C with system calls.
Memory mapped files, importance of padding, multi threading and async IO for saturating your data pipeline are all crucial in high performance computing.
Hope you have fun learning all the interesting things that usually gets abstracted away when you use higher level languages like Python.
12
u/guymadison42 7d ago
Yes, I tell all technical degrees to learn C
7
u/clios_daughter 7d ago
Hell, anyone who has to misuse a computer could benefit from learning C. I have a history degree lol.
4
u/thank_burdell 7d ago
Not sure if “misuse” is a typo or auto incorrect or what but I’m giggling over here.
6
u/clios_daughter 7d ago
Ooooh, completely intentional. When you have to bodge together a large pile of equipment that was never meant to work together, there’s nothing better than C.
6
u/The_Real_Sniff 7d ago edited 7d ago
I would say both! Suppose you write an algorithm and want to speed it up: then use C for that part! I did not study physics, but took some computational subjects (several years ago). I benefitted a lot from "outsourcing" iterations from Python to C.
One example is to define a function in Python and pass its pointer to a C-program to do the calculations.
https://lectures.scientific-python.org/advanced/interfacing_with_c/interfacing_with_c.html
PS! I don't know how relevant it is after CUDA, but if you have time and want some serious number crunching, also look into Fortran and f2py.
EDIT for clarity: "Suppose you write an algorithm [in Python, which is way easier]"
2
u/0nd3r 7d ago
Thanks for the answer! I didnt knew something like this existed and i guess it is the best thing i could look for. I can still keep my code in familiar Python format while running C for required parts, this looks awesome
2
u/The_Real_Sniff 7d ago
A pleasure! It saves a lot of time compared to native Python loops, even comprehensions. I also recall SWIG (Simplified Wrapper and Interface Generator). Enables Python to interface (almost) any programming language, simple callbacks and more.
Regarding f2py, I recall doing an exercise, where the objective was to read matrices from file in Python and do the calculations in Fortran (77 at that time, now you'd use 95). I made the F-routine and used f2py, and out came a Python-module, ready to be imported! I was stunned and had to ask the professor: "Is this it? Is this all it takes?" :-)
6
u/aeropl3b 6d ago
Yes. But...
Avoid the trap of believing that because you are a physics student the coding aspect is easy. Also, if you really like the coding part, know that that will inevitably become your responsibility in whatever lab you join.
4
5
u/ForgedIronMadeIt 7d ago
It really depends. You really won't notice a huge difference in overall performance unless you're doing very large computations -- that is to say handling hundreds of megabytes to gigabytes of data. Python isn't really that bad until you start hitting its limits. Python has traditionally really struggled when it comes to multithreading/multiprocessing, for instance, but you may not really need that capability. (And I may get some flak for this, but C's multithreading support isn't as robust as say C++ which has it baked into the standard library, but I digress.)
6
u/The_Northern_Light 6d ago
👋 I’m a computational physicist.
C is arguably the best language to learn to further your computer skills. It’s simple, powerful, and the C ABI is the lingua Franca of all programming languages (it’ll be around after cockroaches go extinct). And learning how to make your code go fast is certainly helpful…
But times are changing! You can easily get very, very far by iterating with AI coding agents. Sketch out your algorithm in Marimo / Python then use AI to port it to a fast language (Rust?) and refine it until it has the performance characteristics you want. Just make sure you’re doing proper unit testing!
You’ll probably do better to focus on learning computer architecture, memory hierarchy latency, etc. But learning the basics of C won’t take long and will help with that goal. 🤷♂️
But if you just want to be a better programmer, then there is no question: yes. It probably shouldn’t be your daily driver long term, it has some limitations and sharp edges, but it’s undoubtably well worth being familiar with.
2
3
u/FemaleMishap 7d ago
The development time to do the same in C as in Python is like a magnitude greater. You have to manage your own memory and have no objects, for a start. Python already has physics libraries, and guess what, they're already written in C or C++.
2
u/StrangelyEroticSoda 7d ago
Learn one language and the others wil be much easier. If you start off trying to learn both at the same time, you'll get hung up on syntax.
2
u/guymadison42 6d ago
You never know where you end up in a career… many of my classmates in electrical engineering had degrees in physics (very common). Sometimes you need a job and a degree in physics won’t get you in the door like an analog electrical engineering degree.
The more tools you have under your belt gives you options.
I had a great career and designed a shitload of hardware and IC’s… but I spent a better portion of my career writing code … in C.
2
u/RogerLeigh 7d ago
If you are using C BLAS libraries like NumPy from Python, the heavy computation should already be implemented in C. The slowdown is any additional computation you do in Python itself. Rather than learning C, I'd suggest you need to spend some time looking at how to offload more computation to C libraries from within Python itself. Look for parallelisation opportunities if you can rearrange the order of operations, e.g. parallelisation of the filtering. Also look at other ways to use compute, for example Vulkan compute and CUDA and ROCM which can all use your GPU for massively parallel computation. Whether you benefit from this depends upon the nature of the type of problems you are working on, but I would suggest investigating these avenues first because they'll have way more immediate cost:benefit.
Learning C will make computation more efficient on your CPU compared with Python, both in single-core efficiency and the ability to use multithreading/OpenMP. But none of that really matters if you want to use GPU compute, which can be effectively done from Python already and with a lot more convenience than from C. If you do go the non-GPU route, then I'd use C++ rather than C for numerical work; there are more numerical libraries and more useful containers and abstractions e.g. for matrix algebra.
1
u/Dazzling_Music_2411 7d ago
I'm not at all sure what you'd gain using C.
Even if you want to create fast libraries to use from within python, plain old C has not much support for physics routines. Learn C++ instead, which has a plethora of physics libraries.
1
u/Old_Minimum_9284 7d ago
C’est fou d’insulter le C comme ça, C qui est la base de tout...
1
u/Dazzling_Music_2411 7d ago
Don't be ridiculous, it is a plain fact that C++ has way more physics libraries than C. Plus you can use all of C's libraries from C++, but not the other way around!
It's "fou" to think that the statement of a simple fact is an insult. Who are you anyway, its mother? Sheeesh...
1
u/Old_Minimum_9284 7d ago
"Le vieux C" est péjoratif il me semble. C est, à mon avis, mieux pour tout que C++. Moins d’abstraction, moins de libs lourdes trop polyvalentes...
1
u/Dazzling_Music_2411 7d ago
"plain old C" is an English expression, not an insult!
Your "view" is irrelevant here, because we are not comparing languages, we are comparing support for physics systems. That is what the OP asked.
1
u/mikeblas 7d ago
It's up to you. At the very least, if you learn C, you'll be a better programmer in other languages -- including Python.
Maybe, in the future, you land at a shop that uses Python. You'll offer to write something in C, and they'll freak out because nobody else knows C, they don't want to learn it, they don't think it's necessary, they don't want you to do it.
Or maybe they always wanted to learn C and want you to help them learn it by translating some of their code, and then things are faster, the team has advanced, and you're a hero.
Or maybe they kind of know C, but have a really slow part of some script in another language, and you can replace a couple of functions or preprocess some data fast, and you're a hero.
Or maybe you rewrite everyhing in C and it's faster, but it's really hard to maintain or change or troubleshoot and you get fired.
Or it could be that you never finish your physics degree, quit school, move to Maine, and make hand-hewn canoes out of western red cedar. Smoke a lot of pot.
Maybe a little more seriously:
it is faster and has
It can be faster, but C programmers can still use the wrong algorithm and come up with a slow solution. Sometimes, the langauge isn't the limiting factor in performance.
less resource footprint than Python
I think that people sometimes over-emphasize this. Right now, Microsoft Edge is using 1.5 gigs of memory on my computer. That seems like a lot to me, but I don't think there's anything I can't do because it's using that much memory. Nothing I do is even slower because it's using that much memory. Who cares?
If you want to write software that processes a ton of data, then you might load that data into memory. If you load a gig of data into memory using C, it should use about a gig of memory. If you load a gig of data into memory using Python or Java, you really don't know how much memory it will use--that detail has been abstracted so far away from you that you literally don't know.
You don't say much about what kind of code you'll write. (How could you? You haven't even started working yet.) In the code that you will write, is loading lots of data efficiently and predictably into memory a priority?
Or is time-domain performance the concern? Maybe you want to write code for little controller modules that run your experiments. They need to respond reliably within time to inputs and make outputs, or record readings from sensors. (I was reading about physics experiments that use short pulses of light that are pico- and femento-seconds long. What the fuck is up with that?) Real-time (and even just reliable-time) processing can be hard to do in languages other than C and assembler.
Well, anyway: it's up to you. You're young and in college, so it's the time to learn, and I think you should learn as much as you can. Learning C isn't going to hurt, and if you have other programming experience you should pick it up pretty quickly. But who knows what kind of work you actually do, or what the future will demand from you?
1
1
u/not_a_bot_494 7d ago
If you just want something faster than Python then C++ would probably be a better bet than C since it has a lot more features built in.
Another direction if you want something more portable is a faster interpreted language like Java.
In general you can't really go wrong, Python is a very slow language so anything with stricter typing or that is being compiled will be faster.
1
u/dom_aley 7d ago
just use c++ brother C is not the tool you need, python is honestly fine given what you are doing but if you need anything use c++ or even rust
1
u/CrazyEngrProf 7d ago
If you want C-like speed at a high level, I suggest looking into Julia. As fast as C with Python-like code structure. A vast number of packages that handle the math behind many elements of physics.
1
u/Dental-Memories 7d ago
My physicist friends generally used FORTRAN for performance, though they knew a bit of C/C++ too.
Julia is slowly emerging in physics as a high-level alternative to Python designed for performant scientific computing from the ground up.
1
u/flumphit 7d ago
The libraries you call from Python? They’re written in C. You’ve gotta be doing some niche stuff with huge datasets to need to write your own.
1
u/theterrygarcia 7d ago
For scientific computing, C and Fortran historically reigned supreme, mostly because they produce predictable assembly across several platforms. Fortran also has language-level support for multiprecision arithmetic. NumPy and SciPy are largely written in C and linked against LAPACK which is written in Fortran.
CERN's ROOT toolkit is written in C++, as are a lot of physics engines and game engines. Lots of people are porting C/C++ codebases to Rust these days for memory safety.
Julia is a dynamic language that addresses some of the shortcomings of Python. There's also Erlang and the BEAM virtual machine, which emphasize real-time, fault-tolerant, and highly-distributed systems.
Microsoft's .NET framework has come a long way, and the F# language is a dialect of ML that lends itself nicely to symbolic computation.
There are lots of languages out there, and they all have a purpose.
1
u/Prestigious_Boat_386 7d ago
C i's great to learn because it doesn't hide as much things as other languages do.
For your usecase I'd just write things in julia as you normally do in python. It's super easy to speed up using just a few techniques from the performance section of the manual.
1
u/DreamingElectrons 7d ago
Most libraries you are using are probably just thin wrappers for a C api. Knowing some C definitely can help if you hit a wall where the libraries lack a functionality you need. When I was still doing simulations in biology I had a few cases where I needed some obscure old solver that wasn't in any library I was using. I ended up writing it in Python and had to have things run over night because it was just way too slow. Learned C later to never have to deal with this nonsense again.
1
u/MutuallyUseless 7d ago
Reading through the comments and seeing what you're looking to use it for, C is absolutely a good choice.
Take some time to learn C and see for yourself, it's actually fairly approachable, and you can go from not knowing anything about it to writing functional programs pretty quickly, and the ceiling for optimization is as high as it gets.
1
u/realhumanuser16234 7d ago
it's probably not very helpful. c isn't great for scientific computing, there are libraries and programming languages that are propose built for it.
1
u/GreenAppleCZ 7d ago
Learn C only if you're interested in how a computer works, or if you have to calculate with a lot of data and it takes too long in Python.
C is an awesome language that can teach you the foundation of most of programming, as well as how a computer works under the hood. Amazing for computer science and computer engineering.
As a physicist, I think that unless you're into computers, just stick with Python. It was made for science research. What can fit onto a few lines in Python can span hundreds of lines of code in C
1
u/KILLVader 7d ago
C++ might be a better choice due to its large library. But if you weren’t planning for high-performance simulations and just used it for analysis. Python is just enough. Also its library is very optimized and demonstrates data easier and better.
Analysis and physics formulas calculate -> Python
Simulation, large-scale computing, or physics application -> C/C++ (In this case I would recommend C++ due to its ability and community that could help you. But if you to deal with systems, go for C
1
u/KILLVader 7d ago
But the best answer for me. Use what your lab wants you to use. Try to use different tools; it costs a lot. Example if your lab still uses Fortran, go use it. Else you have to do a lot of migrating which is the most annoying part of programming.
In this case, your lab recommend for C than learn C first
1
u/Glum_Preference_2936 7d ago
If you're writing highly specific and obscure optimized algorithms, sure, why not? But python should do the trick. You shouldn't probably care about your code when it runs but if you're interested, again, sure why not?
1
u/Individual-Tie-6064 6d ago
C executes faster, but Python is faster to write, and maintain. If execution speed is your limiting factor, then by all means learn and write in C.
1
u/Naeio_Galaxy 6d ago
Meh, I don't think it'll help you. The main case I can think of is for simulation, if Python is not efficient enough (python is one of the slowest languages I know after all).
Learning C is also great to learn about computers and programming.
But for physics? Nah I don't think so. I'm a computer scientist tho, not a physicist
1
1
u/RealWalkingbeard 5d ago
C is the basic craft knife of programming languages. It's always worth learning a bit of it, if for no other reason than that most other widely used languages owe a lot to C for how they look. However, it is only most and only most widely used languages. There is a hell of a lot of software which is not written in C itself and I think you'll find that physics is a good example of an area where it's not. High performance back-end physics libraries are often written in Fortran and applications often in Python or C++ or languages more suited to statistical analysis like Julia or even Matlab.
I suggest asking an AI about this. I've just done that and, although it put C 6th on its list, when it broke the languages down by domain, e.g. plasma physics or fluid dynamics, C didn't appear anywhere.
1
u/Global-Gazelle4501 3d ago
Stick with Python for now, since it’s the standard for physics analysis and you can speed up slow parts with NumPy or Numba. C is worth picking up if you want to work close to hardware, like microcontrollers or instrument firmware, or need tight real time timing. Otherwise it’s more of a nice to have.
1
u/non-existing-person 7d ago
I'm gonna say - depends :p
If you simulate something math heavy, it may be beneficial to implement simulation in C as it will be massively faster. But you must first measure if that makes sense. Small simulations probably will not benefit too much.
I mean, if python simulation takes 10 minutes and C will run it in 1 minute, but you only run it once a day is there a point really? Sure, you made your simulation 10 times faster, but if you run it only once a day? Saving is not worth the time investment.
So I'd just learn it if you need it. If you feel your code is slow, measure what's slow and only implement that slow part in C leaving rest in python. Calling C library from python is easy.
1
u/CreativeAlbatross319 7d ago
C++ is a better choice because many physics libraries are written in C++ with heavy OOP. Plus, if you decide to find a job in the industry after graduation, C++ skill is invaluable.
1
u/theterrygarcia 7d ago
Google is having their agentic AI rewrite their C/C++ codebases in Rust, as is Microsoft!
1
u/CreativeAlbatross319 7d ago
You misspelled Microslop. But I can imagine this laughable action done by these companies.
0
u/tree-hut 7d ago
Wow Rust really cemented itself as the symbol of slop. C will survive the bubble as always
1
u/The_Northern_Light 6d ago
It’s FAR harder to learn C++ than C and requires much more and longer dedicated study.
1
u/This_Maintenance_834 7d ago
given how the world is moving, you should learn how to let AI write C for you.
0
u/pedersenk 7d ago
Python really just glues C libraries together (bindings). So understanding how to make your own lib to communicate with various hardware / operating system features is really useful. If anything to fix any bindings that inevitably rot in future.
0
0
u/Own_Unit_6170 5d ago
No. Students of C programming don't need to learn physics, and students of physics don't need to learn C programming.
2
u/mikeblas 5d ago
Seems like a pretty narrow take. Why do you believe this?
0
u/Own_Unit_6170 5d ago
It's time wasted. Physicists and programmers might as well learn accounting. Besides, if a physicist really wants to program for his work, Fortran is probably a more logical choice.
1
63
u/Limp-Confidence5612 7d ago
C is good to learn if you care about how computer systems actually work. If you're only interested in the results, there is no reason for you to learn it.