每隔几毫秒写入一个文件的最有效(最快)方法是什么

What is the most efficient (fastest) way to write to a file every few milliseconds?

本文关键字:文件 一个 有效 方法 最快 是什么 几毫      更新时间:2023-10-16

我需要打开一个文件,每隔几毫秒向文件写入一个字节,然后关闭该文件。做这件事最有效的方法是什么?目前,它正在导致高CPU利用率。

编写文件的最快方法是使用系统API。由于您使用的是Windows:https://msdn.microsoft.com/en-us/library/windows/desktop/bb540534(v=vs.85).aspx

HANDLE hfile = CreateFile("file",              // name of the write
                       GENERIC_WRITE,          // open for writing
                       0,                      // do not share
                       NULL,                   // default security
                       CREATE_NEW,             // create new file only
                       FILE_ATTRIBUTE_NORMAL,  // normal file
                       NULL);                  // no attr. template
bErrorFlag = WriteFile( 
                    hfile,           // open file handle
                    DataBuffer,      // start of data to write
                    dwBytesToWrite,  // number of bytes to write
                    &dwBytesWritten, // number of bytes that were written
                    NULL);           // no overlapped structure
CloseHandle(hFile);

此外,在加载应用程序时打开文件,在销毁应用程序时关闭文件,因为打开和关闭文件是缓慢的部分。也就是说,不要每次需要写入时都打开/关闭文件,而是只打开/关闭一次。

这些函数位于<windows.h>中。