有很多关于如何测量循环执行时间的例子,但是在下面的例子中,当调用localtime()
时,我想获取当前的日期和时间,以区分远程服务器上日志(log)文件中的循环迭代:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <libssh/libssh.h>
#define BILLION 1000000000.0
int main(void) {
struct timespec start, finish;
time_t t = time(NULL);
ssh_session session;
int rc;
int session_status;
session = ssh_new();
const char *host = "127.0.0.1";
const char *port = "22";
const char *username = "user";
const char *password = "pass";
char *reply;
ssh_options_set(session, SSH_OPTIONS_HOST, host);
ssh_options_set(session, SSH_OPTIONS_PORT_STR, port);
ssh_options_set(session, SSH_OPTIONS_USER, username);
session_status = ssh_get_status(session);
printf("Session status: %d\n", session_status);
for (int i = 0; i < 4; ++i) {
clock_gettime(CLOCK_REALTIME, &start);
rc = ssh_connect(session);
if (rc != SSH_OK) {
fprintf(stderr, "Error connecting to %s: %s\n", host, ssh_get_error(session));
ssh_free(session);
exit(-1);
}
if (ssh_userauth_password(session, NULL, password) == SSH_AUTH_SUCCESS) {
reply = "Authentication succeeded with incorrect password.";
}
else {
reply = "Authentication failed with incorrect password.";
}
clock_gettime(CLOCK_REALTIME, &finish);
double time_spent = (finish.tv_sec - start.tv_sec) + (finish.tv_nsec - start.tv_nsec) / BILLION;
struct tm tm = *localtime(&t);
printf("[%d-%02d-%02d %02d:%02d:%02d] Status:%s ",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, reply);
printf("Elapsed time: %.4f seconds.\n", time_spent);
ssh_disconnect(session);
}
ssh_free(session);
return (0);
}
运行代码段后,每次迭代的日期和时间都相同.如何显示当前时间?