为什么c++比python快?
1.Python经过了更多层,甚至连数字都是object。
2.Python是解释执行的,和物理机CPU之间多了解释器这层,而C++是编译执行的,直接就是机器码,编译的时候编译器还可以进行一些优化。
python的多线程是假多线程
解释器提供了GIL( Global Interpreter Lock ,全局解释器锁)保证线程数据同步,每个时刻只有一条线程在执行。
可以使用多进程实现并行。
# 多线程
from threading import Thread
def spawn_n_threads(n, target):
threads = []
for _ in range(n):
thread = Thread(target=target)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
# 多进程
from multiprocessing import Process
def spawn_n_processes(n, target):
threads = []
for _ in range(n):
thread = Process(target=target)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
python装饰器
为了代码重用和调用原来的函数实现新的功能
# 传入一个函数,返回新的被装饰了的函数
def timer(func):
def deco():
print("add something 1")
func()
print("add something 2")
return deco
# 用@符号告诉python,foo这个函数被timer装饰了,调用foo会直接调用timer(foo)
@timer
def foo():
print("1000lines")
foo()