- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我的应用程序将一些文件写入光盘,但我意识到在此过程中我正在覆盖现有文件。所以,我需要先检查文件是否存在,然后再执行一些逻辑。
可能有很多文件,因此,我想衡量影响会有多少开销(就时间而言)。因此,我创建了一个控制台应用程序来对其进行测试。
我的代码
using System;
using System.Collections.Generic;
using System.IO;
namespace TimeForFileRead
{
class Program
{
static string myPath = "C:\\Users\\DRook\\Desktop\\temp\\";
static string myPathFile = myPath + "file";
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
DoSomeWork();
Console.WriteLine(" = = = = = =============== = = = = =");
}
Console.ReadKey();
}
static void DoSomeWork()
{
if (!Directory.Exists(myPath))
Directory.CreateDirectory(myPath);
System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
for (int i = 0; i < 1000; i++)
{
using (StreamWriter sw = new StreamWriter(myPathFile + i.ToString() + ".txt"))
{
sw.Write(i.ToString());
}
i++;
}
stopWatch.Stop();
Console.WriteLine("Write only: " + stopWatch.Elapsed);
Directory.Delete(myPath, true);
System.Threading.Thread.Sleep(500);
Directory.CreateDirectory(myPath);
System.Threading.Thread.Sleep(500);
stopWatch.Reset();
stopWatch.Start();
for (int i = 0; i < 1000; i++)
{
if (!File.Exists(myPathFile + i.ToString() + ".txt"))
{
using (StreamWriter sw = new StreamWriter(myPathFile + i.ToString() + ".txt"))
{
sw.Write(i.ToString());
}
}
i++;
}
stopWatch.Stop();
Console.WriteLine("Write and File check: " + stopWatch.Elapsed);
}
}
}
因此,如您所见,它执行了 2 个操作。我是将文件写入磁盘,另一个是检查文件是否已经存在,如果不存在,则写入磁盘。
我的控制台窗口的屏幕截图(结果):
如您所见,奇怪的是首先检查文件是否存在然后写入它几乎总是比直接写入光盘更快。这让我很困惑。这当然是没有意义的。为什么这个额外的开销会提高速度(考虑到 File.Exists()
在我的代码中将始终返回 false,因此不会跳过 Write)?我假设我的代码有错误,但我已经看了一段时间,但我无法理解它。
编辑
根据评论,我稍微改变了顺序,所以我现在先执行 File.Exists()
检查,然后执行只写检查。结果更加夸张(虽然我现在迭代超过 10000 而不是上面代码中的 1000):
编辑2
@MatthewWatson 注意到我的代码有一个错误,我已经更新它以确保总是首先删除该目录。同样的问题仍然存在,但发生率大大降低,但速度差异更大。
using System;
using System.Collections.Generic;
using System.IO;
namespace TimeForFileRead
{
class Program
{
static string myPath = "C:\\Users\\DRook\\Desktop\\temp\\";
static string myPathFile = myPath + "file";
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
DoSomeWork();
Console.WriteLine(" = = = = = =============== = = = = =");
}
Console.ReadKey();
}
static void DoSomeWork()
{
if (Directory.Exists(myPath))
Directory.Delete(myPath, true);
Directory.CreateDirectory(myPath);
System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
for (int i = 0; i < 10000; i++)
{
using (StreamWriter sw = new StreamWriter(myPathFile + i.ToString() + ".txt"))
{
sw.Write(i.ToString());
}
i++;
}
stopWatch.Stop();
Console.WriteLine("Write took : " + stopWatch.Elapsed);
Directory.Delete(myPath, true);
System.Threading.Thread.Sleep(500);
Directory.CreateDirectory(myPath);
System.Threading.Thread.Sleep(500);
stopWatch.Reset();
stopWatch.Start();
for (int i = 0; i < 10000; i++)
{
if (!File.Exists(myPathFile + i.ToString() + ".txt"))
{
using (StreamWriter sw = new StreamWriter(myPathFile + i.ToString() + ".txt"))
{
sw.Write(i.ToString());
}
}
i++;
}
stopWatch.Stop();
Console.WriteLine("Write and check took: " + stopWatch.Elapsed);
}
}
}
最佳答案
太多的代码无法放在评论中 - 简短的回答是 Exists + Write 通常应该比只写花费更长的时间(即使对于现有文件)。
磁盘 IO 不是很可预测(缓存、预热、机器负载、IO 队列、HDD/SSD 模型等),但运行大量迭代(超过 1000 次)的测试需要超过几毫秒应该给你和想法。在我的机器上,Exists+Write 通常需要更长的时间,但也有异常(exception) - 它可能是页面交换干扰或其中一个 VM,谁知道....
这是一个略有修改的测试套件,包含 4 个场景:1.新建文件夹,只写2.新建文件夹,存在+写入3. 现有文件夹和文件(来自步骤 2)只写4.现有文件夹和文件(来自步骤2)存在+写入
代码如下:
class FTest
{
static string myPath = "C:\\Users\\DRook\\Desktop\\temp\\";
static string myPathFile = myPath + "file";
public static void test()
{
for (int i = 0; i < 5; i++)
{
DoSomeWork();
Console.WriteLine(" = = = = = =============== = = = = =");
}
Console.ReadKey();
}
public static void testX1(string path, int index)
{
using (StreamWriter sw = new StreamWriter(path + index.ToString() + ".txt"))
{
sw.Write(index.ToString());
}
}
public static void testX2(string path, int index)
{
if (!File.Exists(path + index.ToString() + ".txt"))
{
using (StreamWriter sw = new StreamWriter(path + index.ToString() + ".txt"))
{
sw.Write(index.ToString());
}
}
else
{
using (StreamWriter sw = new StreamWriter(path +"n"+ index.ToString() + ".txt"))
{
sw.Write(index.ToString());
}
}
}
static void runTestMeasure(Action<string, int> func, int count, string message, bool cleanup)
{
if (cleanup)
{
if (Directory.Exists(myPath)) Directory.Delete(myPath, true);
System.Threading.Thread.Sleep(500);
Directory.CreateDirectory(myPath);
System.Threading.Thread.Sleep(500);
}
System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
for (int i = 0; i < count; i++)
{
func(myPath,i);
}
stopWatch.Stop();
Console.WriteLine(message+": " + stopWatch.Elapsed);
}
static void DoSomeWork()
{
int count = 10000;
runTestMeasure((path, ndx) => { testX1(path, ndx); },count,"Write missing file",true);
System.Threading.Thread.Sleep(5000);
runTestMeasure((path, ndx) => { testX2(path, ndx); }, count, "Write+Exists missing file",true);
System.Threading.Thread.Sleep(5000);
runTestMeasure((path, ndx) => { testX2(path, ndx); }, count, "Write existing file", false);
System.Threading.Thread.Sleep(5000);
runTestMeasure((path, ndx) => { testX2(path, ndx); }, count, "Write+Exists existing file", false);
}
}
自己检查一下,看看它在您的机器上的表现如何。顺便说一句:在 for 循环中使用 i++;
是没有意义的。
编辑:修复了 textX2
代码以在文件存在时创建新文件(备用名称)
关于c# - 检查 File.Exists() 是否提高写入速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19654861/
我有这个代码 var myChart = new FusionCharts("../themes/clean/charts/hbullet.swf", "myChartId", "400", "75
既然写入是立即进行的(复制到内核缓冲区并返回),那么使用 io_submit 进行写入有什么好处? 事实上,它 (aio/io_submit) 看起来更糟,因为您必须在堆上分配写入缓冲区并且不能使用基
我正在使用 mootool 的 Request.JSON 从 Twitter 检索推文。收到它后,我将写入目标 div 的 .innerHTML 属性。当我在本地将其作为文件进行测试时,即 file:
最终,我想将 Vertica DB 中的数据抓取到 Spark 中,训练机器学习模型,进行预测,并将这些预测存储到另一个 Vertica DB 中。 当前的问题是确定流程最后部分的瓶颈:将 Spark
我使用 WEKA 库编写了一个 Java 程序, 训练分类算法 使用经过训练的算法对未标记的数据集运行预测 将结果写入 .csv 文件 问题在于它当前写出离散分类结果(即算法猜测一行属于哪个类别)。我
背景 - 我正在考虑使用 clickonce 通过 clickonce(通过网站)部署 WinForms 应用程序。相对简单的应用程序的要素是: - 它是一个可执行文件和一个数据库文件(sqlite)
是否有更好的解决方案来快速初始化 C 数组(在堆上创建)?就像我们使用大括号一样 double** matrix_multiply(const double **l_matrix, const dou
我正在读取 JSON 文件,取出值并进行一些更改。 基本上我向数组添加了一些值。之后我想将其写回到文件中。当我将 JSONArray 写回文件时,会被写入字符串而不是 JSONArray 对象。怎样才
我为两个应用程序使用嵌入式数据库,其中一个是服务器,另一个是客户端。客户端应用程序。可以向服务器端发送获取数据请求以检索数据并显示在表格(或其他)中。问题是这样的:如何将获取的数据保存(写入)到页面文
是否有更好的解决方案来快速初始化 C 数组(在堆上创建)?就像我们使用大括号一样 double** matrix_multiply(const double **l_matrix, const dou
从问题得出问题:找到所有 result = new ArrayList(); for (int i = 2; i >(i%8) & 0x1) == 0) { result.add(i
由于某种原因,它没有写入 CSV。谁能明白为什么它不写吗? def main(): list_of_emails = read_email_csv() #read input file, cr
关闭。 这个问题是 not reproducible or was caused by typos 。它目前不接受答案。 这个问题是由于错别字或无法再重现的问题引起的。虽然类似的问题可能在这里出现,
我目前正在开发一个保存和加载程序,但我无法获得正确的结果。 编写程序: #include #include #define FILENAME "Save" #define COUNT 6 type
import java.io.*; public class Main2 { public static void main(String[] args) throws Exception {
我需要使用预定义位置字符串“Office”从所有日历中检索所有 iOS 事件,然后将结果写入 NSLog 和 UITextView。 到目前为止,这是我的代码: #import "ViewCo
我正在尝试将 BOOL 值写入 PFInstallation 中的列,但会不停地崩溃: - (IBAction)pushSwitch:(id)sender { NSUserDefaults *push
我以前在学校学过一些简单的数据库编程,但现在我正在尝试学习最佳实践,因为我正在编写更复杂的应用程序。写入 MySQL 数据库并不难,但我想知道让分布式应用程序写入 Amazon EC2 上的远程数据库
是否可以写回到ResourceBundle?目前我正在使用 ResourceBundle 来存储信息,在运行时使用以下内容读取信息 while(ResourceBundle.getBundle("bu
关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。 这个问题是由于错别字或无法再重现的问题引起的。虽然类似的问题可能是on-topi
我是一名优秀的程序员,十分优秀!