简体   繁体   English

对std :: cout对程序性能的影响

[英]Affect on std::cout on performance of the program

I have written a program which would fetch file details and place them in the SQLite database. 我编写了一个程序,该程序将获取文件详细信息并将其放置在SQLite数据库中。 In this process i have observed two scenarios: 在此过程中,我观察了两种情况:

Scenario 1: 方案1:

  1. Loop through each and every file and fill the file details(path) in to the database(sqlite3). 遍历每个文件,并将文件详细信息(路径)填充到数据库(sqlite3)中。
  2. While for each file encountered,keep a counter and print the same via std::cout. 对于遇到的每个文件,请保留一个计数器并通过std :: cout打印该计数器。 Time taken to execute this program:30mins 执行此程序所需时间:30分钟

Scenario 2: 方案2:

  1. Loop through each and every file and fill the file details(path) in to the database(sqlite3). 遍历每个文件,并将文件详细信息(路径)填充到数据库(sqlite3)中。

Time taken to execute this program:7mins 执行此程序所需时间:7分钟

I am very unclear as of why just because of std::cout ,the time taken is 5 times more than that of not printing it? 我还不清楚为什么只是因为std::cout ,所花费的时间是不打印的时间的5倍

Any pointers on this scenario is highly appreciated.Thanks a lot. 非常感谢您对此方案提出任何建议,非常感谢。

Regards, Ravi 问候,拉维

尝试使用std::ios_base::sync_with_stdio(false) ,默认情况下std :: cout与stdio同步

Printing to console is costly. 打印到控制台成本很高。 Usually more time-consuming than writing to a file. 通常比写入文件更耗时。

I bet your code could run in less than a minute. 我敢打赌,您的代码可以在不到一分钟的时间内运行。 Make sure you surround some inserts in a transaction . 确保在事务包含一些插入内容。 You can also use multiple inserts in one statement, like explained in answers to this question . 您也可以在一个语句中使用多个插入内容,例如对此问题的答案中所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM