我想比较使用Python和C++从stdin读取字符串的读取行,并且看到我的C++代码运行速度比等效的Python代码慢一个数量级,这让我很震惊.由于我的C++生锈了,我还不是专家Pythonista,请告诉我,如果我做错了什么或者我是否误解了什么.
(TLDR回答:包括声明:cin.sync_with_stdio(false)或者只是fgets改用.
TLDR结果:一直向下滚动到我的问题的底部并查看表格.)
C++代码:
#include <iostream>
#include <time.h>
using namespace std;
int main() {
string input_line;
long line_count = 0;
time_t start = time(NULL);
int sec;
int lps;
while (cin) {
getline(cin, input_line);
if (!cin.eof())
line_count++;
};
sec = (int) time(NULL) - start;
cerr << "Read " << line_count << " lines in " << sec << " seconds.";
if (sec > 0) {
lps = line_count / sec;
cerr << " LPS: " << lps …Run Code Online (Sandbox Code Playgroud) 嗨,我想了解为什么以下代码使用正则表达式进行拆分字符串拆分
#include<regex>
#include<vector>
#include<string>
std::vector<std::string> split(const std::string &s){
static const std::regex rsplit(" +");
auto rit = std::sregex_token_iterator(s.begin(), s.end(), rsplit, -1);
auto rend = std::sregex_token_iterator();
auto res = std::vector<std::string>(rit, rend);
return res;
}
int main(){
for(auto i=0; i< 10000; ++i)
split("a b c", " ");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
比下面的python代码慢
import re
for i in range(10000):
re.split(' +', 'a b c')
Run Code Online (Sandbox Code Playgroud)
这里的
> python test.py 0.05s user 0.01s system 94% cpu 0.070 total
./test 0.26s user 0.00s system 99% cpu 0.296 total …Run Code Online (Sandbox Code Playgroud) 我做了一个测试来比较几种语言的字符串操作,以便为服务器端应用程序选择一种语言.结果似乎很正常,直到我最终尝试了C++,这让我感到非常惊讶.所以我想知道我是否错过了任何优化并来到这里寻求帮助.
测试主要是密集的字符串操作,包括连接和搜索.测试在Ubuntu 11.10 amd64上进行,GCC版本为4.6.1.该机器是戴尔Optiplex 960,配备4G内存和四核CPU.
def test():
x = ""
limit = 102 * 1024
while len(x) < limit:
x += "X"
if x.find("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0) > 0:
print("Oh my god, this is impossible!")
print("x's length is : %d" % len(x))
test()
Run Code Online (Sandbox Code Playgroud)
结果如下:
x's length is : 104448
real 0m8.799s
user 0m8.769s
sys 0m0.008s
Run Code Online (Sandbox Code Playgroud)
public class test {
public static void main(String[] args) {
int x = 0;
int limit = 102 * 1024;
String s="";
for (; s.length() …Run Code Online (Sandbox Code Playgroud) 我有一个用Python和Haskell编写的简单脚本.它读取一个包含1,000,000个换行符分隔整数的文件,将该文件解析为整数列表,对其进行快速排序,然后将其写入已排序的其他文件.此文件的格式与未排序的文件相同.简单.
这是Haskell:
quicksort :: Ord a => [a] -> [a]
quicksort [] = []
quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)
where
lesser = filter (< p) xs
greater = filter (>= p) xs
main = do
file <- readFile "data"
let un = lines file
let f = map (\x -> read x::Int ) un
let done = quicksort f
writeFile "sorted" (unlines (map show done))
Run Code Online (Sandbox Code Playgroud)
这是Python:
def qs(ar):
if len(ar) == 0:
return ar
p …Run Code Online (Sandbox Code Playgroud) 我正在使用以下bash命令模式运行memcached:
memcached -vv 2>&1 | tee memkeywatch2010098.log 2>&1 | ~/bin/memtracer.py | tee memkeywatchCounts20100908.log
Run Code Online (Sandbox Code Playgroud)
尝试跟踪无与伦比的获取到平台键的集合.
memtracer脚本位于下方并按预期工作,只有一个小问题.看到中间日志文件大小,memtracer.py在memkeywatchYMD.log大小约为15-18K之前不会开始输入.有没有更好的方法来读取stdin或者可能是将缓冲区大小降低到1k以下以获得更快的响应时间?
#!/usr/bin/python
import sys
from collections import defaultdict
if __name__ == "__main__":
keys = defaultdict(int)
GET = 1
SET = 2
CLIENT = 1
SERVER = 2
#if <
for line in sys.stdin:
key = None
components = line.strip().split(" ")
#newConn = components[0][1:3]
direction = CLIENT if components[0].startswith("<") else SERVER
#if lastConn != newConn:
# lastConn = newConn
if direction == CLIENT:
command = SET if …Run Code Online (Sandbox Code Playgroud) 编辑:我添加了两个基准,比较realloc与C数组的使用和reserve()与std :: vector的使用.从最后的分析来看,似乎realloc影响很大,即使只调用了30次.检查文档我想这是因为realloc可以返回一个全新的指针,复制旧的指针.为了完成该场景,我还添加了用于在初始化期间完全分配阵列的代码和图形.区别reserve()是有形的.
编译标志:只有图中描述的优化,用g ++编译,仅此而已.
原始问题:
std::vector当我添加10亿个整数并且第二个代码比使用向量的代码快得多时,我做了vs新/删除数组的基准测试,尤其是在启用优化的情况下.
我怀疑这是由内部调用realloc的向量太多次引起的.如果vector每次填充时它的大小不会增加一倍就会出现这种情况(这里数字2没有什么特别之处,重要的是它的大小几何增长).在这种情况下,对realloc的调用只会O(log n)代替O(n).
如果这是导致第一个代码缓慢的原因,我怎么能告诉std :: vector几何增长?
请注意,调用reserve一次会在这种情况下工作,但不是在更普遍的情况下,事先不知道push_back的数量.
黑线
#include<vector>
int main(int argc, char * argv[]) {
const unsigned long long size = 1000000000;
std::vector <int> b(size);
for(int i = 0; i < size; i++) {
b[i]=i;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
蓝线
#include<vector>
int main(int argc, char * argv[]) {
const int size = 1000000000;
std::vector <int> b;
for(int i = 0; i < size; i++) { …Run Code Online (Sandbox Code Playgroud)