语言特性

为什么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()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值