我试图描述我的python脚本,以弄清楚为什么花费时间来处理数据。使用cProfile和pstats,我得到了这个结果:
Tue Jan 20 08:49:08 2015 C:/Python27/profilingResults/profile_dump_1
24236665 function calls (24236295 primitive calls) in 1566.843 seconds
Random listing order was used
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 C:\Python27\Lib\numbers.py:270(Rational)
2745 0.003 0.000 0.010 0.000 C:\Python27\Lib\decimal.py:1768(_round_half_even)
2 0.000 0.000 0.000 0.000 C:\Python27\Lib\calendar.py:71(__init__)
1 0.000 0.000 0.000 0.000 C:\Python27\Lib\logging\__init__.py:458(format)
1 0.000 0.000 0.000 0.000 C:\Python27\Lib\logging\__init__.py:1281(handle)
1 0.000 0.000 0.000 0.000 C:\Python27\Lib\atexit.py:6(<module>)
1 0.000 0.000 0.000 0.000 C:\Python27\Lib\decimal.py:321(Overflow)
9539 1548.536 0.162 1548.536 0.162 {method 'execute' of 'psycopg2._psycopg.cursor' objects}
最后一行似乎不行,但我没有得到它。为什么游标会导致这个成本呢?
import psycopg2 as psycopg
try:
connectStr = "dbname='postgis20' user='postgres' password='' host='localhost'"
cx = psycopg.connect(connectStr)
cu = cx.cursor()
logging.info("connected to DB")
except:
logging.error("could not connect to the database")
global cx
try:
cu.execute("INSERT INTO taxi (userid,carNum) SELECT '"+str(msg['UserID'])+"',"+str(msg['CarNumber']))
cu.execute
cu.execute
cu.execute
cu.execute
..
..
..
.
except Exception, err:
print('ERROR: %s\n' % str(err))
cx.commit()
cx.commit()
答案 0 :(得分:1)
游标成本是由于在第二个代码块中调用了execute函数。(通常执行sql查询并返回结果将比任何基本操作花费更多的时间)
您可以在分析here
时找到很多帮助答案 1 :(得分:1)
您有9539个插页,每个插页0.162毫秒。听起来很正常。您可以使用批量插入或copy_from来加速整个过程。