+ 1
Which will use the more CPU?
I heard that not closing file may use extra CPU. So if we have a while loop, is it better to use with open? Since Closing and Opening can slow down. 1) a = 0 while a != 10: with open("test.txt") as file: print(file.read(a)) 2) a = 0 file = open("test.txt") while a != 10: print(file.read(a)) file.close() I know this is silly but if it's big project, which will be better?
3 Answers
+ 5
The first snippet will, for obvious reasons, be more expensive. This is because as you are opening a file and closing it in each iteration of the loop, that is, 10 times. Whereas in the 2nd code, you're only doing it once.
+ 3
CPU work increases where there exists calculation, so the more tedious the calculation, the more CPU activity. File related activities is more related with I/O or disk activity (in case of disks), not sure how it is with SSD or flash drives.
Unclosed file may trigger access violation error, especially when the file is opened exclusively. But even that only happen while the program opening the file is running. Once the program is terminated, the file should normally be accessible again.
+ 2
use task manager for that lol, if you need to check which one will take more CPU's time