打印当前日期和时间,记录微秒级时间日志的C程序

打印当前日期和时间

C程序:

#include <time.h> 
#include <stdio.h> 

int main(void) 
{ 
	time_t  t; 
	time(&t);
	printf("The Calendar Time now is %s\n",ctime(&t));
	return 0; 
} 


编译后运行程序,输出结果:

The Calendar Time now is Fri Jun 28 10:06:18 2013

Press any key to continue

附加对应的python程序:

import time
print time.ctime()

执行,输出结果:

'Fri Jun 28 10:10:31 2013'

参考资料:

python time模块详解

http://blog.csdn.net/kiki113/article/details/4033017


记录微秒级时间日志

logtest.h

#ifndef LOGTEST_H
#define LOGTEST_H

#include <stdio.h>
#include <time.h>
#include <sys/time.h>

extern int Debugmode;
extern int Logmode;
extern int Testmode;

// log file
extern const char *Filepath;

// time parameters
extern time_t T;
extern struct timeval Start, End;


// write log with timestamp
int writelog(char* str);

// performance test
int tick();
int tock();

#endif


logtest.c

#include "logtest.h"

int Debugmode=0;
int Logmode=0;
int Testmode=0;

// log file
const char *Filepath="logfile.txt";

// time parameters
time_t T;
struct timeval Start, End;

// write log with timestamp
int writelog(char* str)
{
    FILE* logfilep;

    if(Debugmode != 0){
        fputs(str, stdout); 
        fputs("\n", stdout);
    }
    if(Logmode != 0){
        time(&T);
        if ((logfilep = fopen(Filepath,"a+"))==NULL) {
            return -1;
        }
        fprintf(logfilep, "The calendar time now is %s\n",ctime(&T));
        fprintf(logfilep, "%s\n\n", str);
        fclose(logfilep);
    }
    return 0;
}

// performance test
int tick()
{
    if(Testmode != 0){
    	gettimeofday(&Start, NULL);
    }
    return 0;
}

int tock()
{
    FILE* logfilep;
	
    if(Testmode != 0){
        gettimeofday(&End, NULL);
        if ((logfilep = fopen(Filepath,"a+"))==NULL) {
            return -1;
        }
        int dt = 1000000 * (End.tv_sec - Start.tv_sec) + (End.tv_usec - Start.tv_usec);
        fprintf(logfilep, "The time difference is %d us\n\n", dt);
        fclose(logfilep);
    }
    return 0;
}

makefile:


C_COMPILER := gcc
RM := rm -rf 

EXE := ./main

.PHONY: all clean

# All Target
all: $(EXE)

# Add inputs and outputs from these tool invocations to the build variables 
LIB_DIR := 
LIBS := 
OBJS := ./main.o
USER_OBJS := ./logtest.o

# Tool invocations
$(EXE): $(OBJS) $(USER_OBJS)
	@echo 'Building target: $@'
	@echo 'Invoking: GCC C Linker'
	$(C_COMPILER) -ldl $(LIB_DIR) $(LIBS) -o $@ $^
	@echo 'Finished building target: $@'
	@echo ' '

# All of the sources participating in the build are defined here
INCLUDE_DIR := -I/usr/local/openssl/include

# Each subdirectory must supply rules for building sources it contributes
./%.o: ./%.c
	@echo 'Building file: $<'
	@echo 'Invoking: GCC C Compiler'
	$(C_COMPILER) -O0 -g3 -Wall $(INCLUDE_DIR) -o $@ -c $<
	@echo 'Finished building: $<'
	@echo ' '

clean:
	-$(RM) $(OBJS) $(USER_OBJS) $(EXE)
	-@echo ' '

.SECONDARY:




你可能感兴趣的:(打印当前日期和时间,记录微秒级时间日志的C程序)