Python实战(6)单线程和多线程导入mysql数据对比测试
单线程脚本
导入文件的行数
# wc -l /data/logs/testlog/20120219/testlog1/*
1510503 total
- # -*- coding: utf-8 -*-
- #!/usr/bin/env python
- #create database pythondata
- #create table log (logline varchar(500));
- #grant all on pythondata.* to 'pyuser'@'localhost' identified by "pypasswd";
- import MySQLdb
- import os
- import time
- def writeLinestoDb(sql,content):
- conn=MySQLdb.connect(host="localhost",user="pyuser",passwd="pypasswd",db="pythondata")
- cur =conn.cursor()
- cur.executemany(sql,content)
- cur.close()
- conn.commit()
- conn.close()
- def readLinestoList(path):
- alllines=[]
- for file in os.listdir(path):
- files=os.path.join(path,file)
- for line in open(files):
- alllines.append(line)
- return alllines
- def main():
- insertsql ="INSERT INTO log(logline) VALUES(%s)"
- alllines=readLinestoList('/data/logs/testlog/20120219/testlog1')
- for line in alllines:
- content=line.strip()
- print content
- writeLinestoDb(insertsql,content)
- time.sleep(10)
- if __name__=="__main__":
- print('starting at:',time.ctime())
- main()
- print('ending at:',time.ctime())
('starting at:', 'Tue Mar 27 11:09:20 2012')
('ending at:', 'Tue Mar 27 11:13:20 2012')
耗时4分钟
mysql> select count(*) from log ;
+----------+
| count(*) |
+----------+
| 1510551 |
+----------+
多线程脚本
- # -*- coding: utf-8 -*-
- #!/usr/bin/env python
- import MySQLdb
- import os
- from time import ctime
- from threading import Thread
- from Queue import Queue
- in_num_thread=10
- out_num_thread=10
- in_queue=Queue()
- out_queue=Queue()
- def listDir(path):
- for filename in os.listdir(path):
- in_queue.put(os.path.join(path,filename))
- def readFile(iq,in_queue):
- filelines=[]
- while True:
- file=in_queue.get()
- for line in open(file):
- filelines.append(line)
- out_queue.put(filelines)
- in_queue.task_done()
- def writeLinestoDb(oq,out_queue):
- sql=insertsql ="INSERT INTO log(logline) VALUES(%s)"
- while True:
- content=out_queue.get()
- conn=MySQLdb.connect(host="localhost",user="pyuser",passwd="pypasswd",db="pythondata")
- cur =conn.cursor()
- cur.executemany(sql,content)
- cur.close()
- conn.commit()
- conn.close()
- out_queue.task_done()
- def main():
- listDir('/data/logs/testlog/20120219/testlog1')
- for iq in range(in_num_thread):
- worker=Thread(target=readFile,args(iq,in_queue))
- worker.setDaemon(True)
- worker.start()
- print "Readfile Main Thread Waiting at",ctime()
- in_queue.join()
- print "Readfile Done at,",ctime()
- for oq in range(out_num_thread):
- worker=Thread(target=writeLinestoDb,args(oq,out_queue))
- worker.setDaemon(True)
- worker.start()
- print "Insert into mysql Main Thread at",ctime()
- out_queue.join()
- print "Insert into mysql at,",ctime()
- if __name__=="__main__":
- print('starting at:',time.ctime())
- main()
- print('ending at:',time.ctime())
- 数据库位于本机
- ('starting at:', 'Tue Mar 27 10:57:01 2012')
Readfile Main Thread Waiting at Tue Mar 27 10:57:01 2012
Readfile Done at, Tue Mar 27 10:57:04 2012
Insert into mysql Main Thread at Tue Mar 27 10:57:04 2012
Insert into mysql at, Tue Mar 27 11:03:34 2012
('ending at:', 'Tue Mar 27 11:03:34 2012')
mysql> select count(*) from log ;
+----------+
| count(*) |
+----------+
| 3676015 |
+----------+ - 两次个数据不一致,多线的导入有问题。
服务器配置4G8核,mysql本地 两个脚本在同一台机器上运行
多线程脚本改进
- #!/usr/bin/env python
- #create table log ( logline varchar(300));
- #grant all on pythondata.* to 'pyuser'@'localhost' identified by "pypasswd"
- import MySQLdb
- import os
- import sys
- from time import ctime
- from threading import Thread
- from Queue import Queue
- num_thread=10
- queue=Queue()
- def listDir(path):
- file_list=[]
- for filename in os.listdir(path):
- file_list.append(os.path.join(path,filename))
- return file_list
- def readFile(file):
- alllines=[]
- for line in open(file):
- alllines.append(line)
- return alllines
- def writeLinestoDb(q,queue):
- sql=insertsql ="INSERT INTO log(logline) VALUES(%s)"
- while True:
- content=queue.get()
- conn=MySQLdb.connect(host="localhost",user="pyuser",passwd="pypasswd",db="pythondata")
- cur =conn.cursor()
- cur.executemany(sql,content)
- cur.close()
- conn.commit()
- conn.close()
- queue.task_done()
- def main():
- print "Readfile Start at,",ctime()
- for file in listDir('/data/logs/testlog/20120219/testlog1'):
- queue.put(readFile(file))
- print "Readfile Done at,",ctime()
- for q in range(num_thread):
- worker=Thread(target=writeLinestoDb,args=(q,queue))
- worker.setDaemon(True)
- worker.start()
- print "Insert into mysql Main Thread at",ctime()
- queue.join()
- print "Insert into mysql at,",ctime()
- if __name__=="__main__":
- print('starting at:',ctime())
- main()
- print('ending at:',ctime())
结果
('starting at:', 'Tue Mar 27 14:32:05 2012')
Readfile Start at, Tue Mar 27 14:32:05 2012
Readfile Done at, Tue Mar 27 14:32:07 2012
Insert into mysql Main Thread at Tue Mar 27 14:32:08 2012
Insert into mysql at, Tue Mar 27 14:34:31 2012
('ending at:', 'Tue Mar 27 14:34:31 2012')
mysql> select count(*) from log;
+----------+
| count(*) |
+----------+
| 1510551 |
+----------+
读用了2秒中,插入使用2分23秒
第一个多线程脚本错误的原因是传入队列的数据问题。 还有一个问题,读的文件超过物理内存和虚拟内存的总量,会造成内存溢出程序挂掉,解决办法每次读取指定行
Python实战(6)单线程和多线程导入mysql数据对比测试的更多相关文章
- Sqoop导入mysql数据到Hbase
sqoop import --driver com.mysql.jdbc.Driver --connect "jdbc:mysql://11.143.18.29:3306/db_1" ...
- solr7.4创建core,导入MySQL数据,中文分词
#solr版本:7.4.0 一.新建Core 进入安装目录下得server/solr/,创建一个文件夹,如:new_core 拷贝server/solr/configsets/_default/con ...
- 【实战】使用 Kettle 工具将 mysql 数据增量导入到 MongoDB 中
最近有一个将 mysql 数据导入到 MongoDB 中的需求,打算使用 Kettle 工具实现.本文章记录了数据导入从0到1的过程,最终实现了每秒钟快速导入约 1200 条数据.一起来看吧~ 一.K ...
- 如何导出和导入mysql数据(数据迁移)
. 导出数据库数据 mysqldump -uroot -p dp_db > dumpout.sql 其中 root是账户名 dp_db是需要导出的数据库名称 dumpout.sql存储导出的数据 ...
- HeidiSQL工具导出导入MySQL数据
有时候,为了数据方便导出导入SQL,我们可以借助一定的工具,方便我们队数据库的移植,可以达到事半功倍的效果.在这里,就给大家简单的介绍一款能方便导出或者导入MySQL的数据. ①首先,选择你要导出的数 ...
- excel导入mysql数据
excel加载mysql数据 1.第一步,选择从mysql导入数据 2.单击会出现弹框: 3.可能有的同学的,这里缺少插件,例如: 4.去下载 这个 插件安装即可.https://dev.mysql. ...
- 【Python实战】模块和包导入详解(import)
1.模块(module) 1.1 模块定义 通常模块为一个.py文件,其他可作为module的文件类型还有".pyo".".pyc".".pyd&qu ...
- python将Excel文件内容导入Mysql数据
为了方便起见,将所有字段类型设置为str,理解mysql的语法这个玩意贼简单 # _*_ coding:utf-8 _*_import pandas as pd #先装个pandas ,pip ins ...
- 命令行导入mysql数据
找到mysql安装目录(bin) 进入mysql mysql -u root -p 123 选中数据库 use 数据库名 导入sql source sql数据库路径
随机推荐
- 2017ICPC北京赛区网络赛 Minimum(数学+线段树)
描述 You are given a list of integers a0, a1, …, a2^k-1. You need to support two types of queries: 1. ...
- linux 安装crontab执行定时任务
转载:https://www.cnblogs.com/xiaoluo501395377/archive/2013/04/06/3002602.html http://yangqijun.iteye.c ...
- 前端笔记 (2.CSS)
知识点借鉴于慕课网,菜鸟教程和w3shool CSS方面: CSS全称为“层叠样式表”,它主要是用于定义HTML内容在浏览器内的显示样式,如文字大小.颜色.字体加粗等. 使用CSS样式的一个好处是通过 ...
- 推荐系统-0X-电影推荐与结果评估
import spark.sql import org.apache.spark.sql.types._ import org.apache.spark.mllib.recommendation.AL ...
- ERROR: gnu-config-native-20150728+gitAUTOINC+b576fa87c1-r0 do_unpack: Function failed: Fetcher failure: Fetch command failed with exit code 128, output: fatal: the '--set-upstream' option is no longer
/********************************************************************** * ERROR: gnu-config-native-2 ...
- MarkDown常用语法表
MarkDown常用语法表 本文提供全流程,中文翻译.Chinar坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) 1 Title - 标题 2 H ...
- HDU - 4454: Stealing a Cake (圆上三分)
pro:给定一个蛋糕,一个矩阵房子,一只蚂蚁.最开始三者两两相离,问蚂蚁触摸到蛋糕后再触摸矩阵的最短距离.结果保留两位小数,坐标的绝对值<1e4: sol:由于坐标不大,而且精度要求不高,不难想 ...
- day022 python (re模块和 模块)
re模块是python提供的一套关于正则表达式的模块.核心功能有四个: 1.findall (查找所有,返回list) lst=re.findall("m",'salalwmaop ...
- python time模块使用笔记(更新)
import time 添加time模块 关于时间和时间戳: 时间是指日常生活中用的,如某年某月某日 时间戳是一个时间长度,是时间关于一个初始时间(好像是1970.1.1)的秒数 localtime方 ...
- 从简单的mongodb example 的观察
https://github.com/no7dw/mongodb-example 这是最基础的连接查询.(branch master) var MongoClient = require('mongo ...