我正在尝试为我的C ++程序创建一个日志文件。我的目标是在程序的两点放置两个时间戳,并在文件中打印这两点之间的CPU时间周期。我这样做是因为我想知道代码的哪些部分最耗时,因此可以进行改进(因此可能要测量几块代码)。到目前为止,我已经制作了一个函数,该函数在被调用时将作为参数传递的字符串打印到文件中:
#define LOGFILE "myprog.log"
void Log (std::string message){
std::ofstream ofs;
ofs.open(LOGFILE, std::ofstream::out | std::ios::app);
ofs << message << std::endl;
ofs.close();
}
Run Code Online (Sandbox Code Playgroud)
但是,我很难弄清楚如何打印CPU时间戳。首先,我不知道应该使用哪种时间测量格式(我应该使用chrono还是time_t类型?)我正在尝试打印时间段,因此,如果存在持续时间类型(我会我尝试了chrono :: duration,但似乎需要C ++ 11支持)。其次,鉴于我知道要使用哪种类型,如何将其打印到文件中?有没有一种方法可以将该类型转换为字符串?还是可以将其直接传递给函数并以某种方式打印?
最近几天这让我很烦恼,我似乎无法弄清楚,因此任何输入都会很有帮助。提前致谢!
我正在尝试使用 fscanf 来读取和打印屏幕上的每个字符,但是在运行程序时出现分段错误(核心转储)。这是我的代码:
#include <stdio.h>
main(int argc, char * argv[]) {
int *a ;
FILE *input;
if (argc>=2) {
input= fopen(argv[1],"r");
if (input!=NULL) {
while (feof(input)==0) {
fscanf(input,"%d\n",a);
printf("%d\n",*a);
}
fclose(input);
} else {
printf("Error!\n");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我提供文件作为参数,如下所示:
./myprog input.txt
Run Code Online (Sandbox Code Playgroud)
该文件input.txt包含以下内容:
23
47
55
70
Run Code Online (Sandbox Code Playgroud)