关于python和c++声明数组的区别

本文最后更新于 2023年8月22日 下午

一把米诺!

刚刚在写题的时候发现自己的代码流程和答案一模一样,但是自己却超时了,可答案却不会。

于是我当即把评测机器的马没收了

于是我抱着科学求知的精神逐步替换代码,用控制变量的科学方法找出了问题所在(`ゥ´ )。

先说结论:
t = [0] * n 来翻译 int t[n] 非常方便,这样也能把c中的编程经验搬运到python中来,然而,python这样的声明方式的时间复杂度不是O(1)的。

所以在python中录入数据是最好使用append指令来逐个添加。否则就会有数组声明的时间浪费,在数据量大的时候非常难受。


接下来是我的实验:

python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import time

start = time.process_time()
for i in range(100000):
x = [0] *100000
del x
end = time.process_time()
print(f'数组创建100000次时间:{end - start}s')

start = time.process_time()
for i in range(1000000):
t = 114514
del t
end = time.process_time()
print(f'变量创建100000*10次时间:{end - start}s')
``````

输出:

数组创建100000次时间:13.390625s
变量创建100000*10次时间:0.0625s

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

可以看到数组和变量创建速度相差巨大,由于变量创建相比数组创建实在快太多,所以常量的创建次数要多上十倍,否则只会显示0.0秒.

c++:

```cpp
#include<bits/stdc++.h>
#include<ctime>
using namespace std;
int main(){
clock_t start,end;
start = clock();
double time;
for(long long i = 1; i <= 10000000000;i++){
int x [1000000];
}

end = clock();

time = static_cast<double>(end-start)/CLOCKS_PER_SEC;
cout<<"声明数组"<<time<<endl;

start = clock();

for(long long i = 1; i <= 10000000000;i++){
int x;
}

end = clock();

time = static_cast<double>(end-start)/CLOCKS_PER_SEC;
cout<<"声明变量"<<time<<endl;


return 0;
}

输出:

1
2
声明数组2.519
声明变量2.49

可以看到,c++里声明数组和声明变量的速度差距非常小。


所以用python的时候非特殊情况不要直接用t = [0] * n声明数组。

还是说只有我现在才知道这点?⊂彡☆))д`)


关于python和c++声明数组的区别
https://bainianlaoyao.github.io/2023/02/21/typecho-recovered-60-关于python和c-plus-plus声明数组的区别/
作者
百年老妖
发布于
2023年2月21日
许可协议