【发布时间】:2025-12-29 12:35:08
【问题描述】:
您好,这是我的第一篇文章,我正在学习如何编写代码,所以从技术上讲我是新手。
我正在学习 python 我仍然处于非常基础的状态,我开始了解 if 语句,我尝试将它与其他概念(函数定义、输入、变量)混合,以便获得更广泛的 python 视野,我写了一些代码,并没有具体了解我想做什么我只是想混合我到目前为止所学的所有内容,所以可能我过度执行它并且它不实用,当我运行它时它“工作”。
我的问题不是关于如何更高效或使用更少的代码,而是关于所有编程中的代码顺序。在这里,我将展示 2 种不同顺序的代码,它们使用完全相同的代码(但顺序不同)给出相同的结果。
关于 (1) 我在第一行定义了一个函数。
关于 (2) 我在第 5 行使用它时定义了更接近的相同函数。
哪个更快?正在定义一个“更接近”我需要的函数,这对于大型程序的复杂性来说是不切实际的(但它是否使它更快),或者定义一个函数“远离”我需要它在运行时使更大的程序变慢(但也更实用)。
(1)
def t(n1,n2):
v=n1-n2
return abs(v)
a = int(input('how old are you? \n'))
b = int(input('how old is your best friend? \n'))
c=t(a,b)
if a==b:
print ('you are both the same age')
else:
print('you are not the same age\nthe difference of years is %s year(s)' % c)
input()
(2)
a = int(input('how old are you? \n'))
b = int(input('how old is your best friend? \n'))
def t(n1,n2):
v=n1-n2
return abs(v)
c=t(a,b)
if a==b:
print ('you are both the same age')
else:
print('you are not the same age\nthe difference of years is %s year(s)' % c)
input()
【问题讨论】:
-
除非您有什么需要担心的,否则不要担心速度。如果你有一大段代码运行速度太慢而你不喜欢,首先看看你能不能想出一个更好的算法。
-
@RolandSmith 我并不担心,我只是想知道它是否会有所作为。
-
如果你想测量速度,你应该使用profiler。
标签: python performance optimization