faker用于生成数据,php和python都有此包
php版本
composer require fzaninotto/faker
composer require cakephp/orm
require './vendor/autoload.php';
use Cake\Datasource\ConnectionManager;
use Cake\ORM\TableRegistry;
set_time_limit(0);
function convert($size)
{
//友好显示size
$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];
}
function microtime_float()
{
//返回微妙
list($usec, $sec) = explode(" ", microtime());
return ((float) $usec + (float) $sec);
}
ConnectionManager::setConfig('default', [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => true,
'host' => 'localhost',
'username' => 'root',
'password' => 'asdqwe123',
'database' => 'test',
'encoding' => 'utf8',
'timezone' => 'UTC',
'cacheMetadata' => false // If set to `true` you need to install the optional "cakephp/cache" package.
]);
$faker = Faker\Factory::create('zh_CN');
$Users = TableRegistry::get('User');
$m = 1000; //循环1000次
$start = microtime_float();
while ($m > 0) {
$m--;
$n = 1000;
$data = [];
while ($n > 0) {//每次循环批量插入1000条
$n--;
$data[] = [
'username' => $faker->name,
'age' => rand(10, 70),
'sex' => rand(0, 1),
'address' => $faker->address,
'ctime' => $faker->dateTime
];
echo 'speed memory:' . convert(memory_get_usage()) . "\r\n"; //打印内存占用情况
}
$entities = $Users->newEntities($data);
$result = $Users->saveMany($entities);
}
$end = microtime_float();
$speed_time = $end - $start;
echo 'speed time:' . $speed_time . ' second' . "\r\n";
php create.php #运行脚本
python版本
# coding=utf-8
from faker import Factory
import uniout
import logging
import threading
import random
import time
from datetime import datetime
from orator import DatabaseManager, Model
print "开始..."
fake = Factory.create('zh_CN')
# 创建 日志 对象
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
# Connect to the database
config = {
'mysql': {
'driver': 'mysql',
'host': 'localhost',
'database': 'test',
'user': 'root',
'password': 'asdqwe123',
'prefix': ''
}
}
db = DatabaseManager(config)
Model.set_connection_resolver(db)
class User(Model):
__table__ = 'user'
pass
thread_nums = 10
ARR = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
LAST = ('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2')
def makeIdNo():
u''' 随机生成新的18为身份证号码 '''
t = time.localtime()[0]
x = '%02d%02d%02d%04d%02d%02d%03d' % (random.randint(10, 99),
random.randint(01, 99),
random.randint(01, 99),
random.randint(t - 80, t - 18),
random.randint(1, 12),
random.randint(1, 28),
random.randint(1, 999))
y = 0
for i in range(17):
y += int(x[i]) * ARR[i]
return '%s%s' % (x, LAST[y % 11])
def insert_user(thread_name, nums):
logger.info('开启线程%s' % thread_name)
for _ in range(nums):
email = fake.email()
job = fake.job()
address = fake.address().encode('utf-8')
password = fake.md5()
text = fake.text().encode('utf-8')
username = str(fake.user_name())
truename = fake.name().encode('utf-8')
create_time = fake.date_time_between_dates(
datetime_start=datetime(2017, 1, 1, 0, 0, 0),
datetime_end=datetime(2017, 8, 12, 0, 0, 0, 0))
create_time = str(create_time)
company = fake.company().encode('utf-8')
# Create a new record
user = User()
user.tel = fake.phone_number()
user.username = username
user.truename = truename
user.job = job
user.company = company
user.password = password
user.email = email
user.id_no = makeIdNo()
user.city_id = random.randint(1, 290)
user.address = address
user.summary = text
user.gender = random.randint(1, 2)
user.age = fake.random_int(10,50)
user.site = fake.uri()
user.uuid = fake.uuid4()
user.save()
for i in range(thread_nums):
t = threading.Thread(target=insert_user, args=(i, 400000))
t.start()
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tel` varchar(20) NOT NULL,
`profile_id` int(11) NOT NULL DEFAULT '0',
`username` varchar(20) NOT NULL,
`truename` varchar(10) NOT NULL,
`job` varchar(100) NOT NULL DEFAULT '',
`company` varchar(100) NOT NULL DEFAULT '',
`password` varchar(50) NOT NULL,
`email` varchar(30) NOT NULL,
`id_no` varchar(20) NOT NULL,
`city_id` varchar(10) NOT NULL DEFAULT '',
`address` varchar(50) NOT NULL,
`summary` varchar(2000) NOT NULL,
`gender` tinyint(4) NOT NULL,
`age` tinyint(4) NOT NULL,
`site` varchar(100) NOT NULL DEFAULT '',
`uuid` varchar(50) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='测试用户表';
网友评论